2 回答

TA貢獻1783條經驗 獲得超4個贊
試試下面的代碼
result = ''.join([i.strip().replace('"', '') for i in anchor.strings if i.strip()][:-1])
print(result)
輸出
'This is a test string'

TA貢獻1827條經驗 獲得超8個贊
根據您的問題和評論,我認為獲取子字符串的索引并對 HTML 的整個子集進行操作可以滿足您的需求。
讓我們首先創建一個函數來檢索子字符串的所有索引(參見@AkiRoss 的回答):
def findall(p, s):
i = s.find(p)
while i != -1:
yield i
i = s.find(p, i+1)
然后使用它來查找<b>和的出現</b>。
opening_b_occurrences = [i for i in findall('<b>', html)]
# has the value of [21, 40, 58]
closing_b_occurrences = [i for i in findall('</b>', html)]
# has the value of [28, 44, 67]
現在您可以使用該信息來獲取 HTML 的子字符串來進行文本提?。?/p>
first_br = opening_b_occurrences[0]
last_br = closing_b_occurrences[-1] # getting the last one from list
text_inside_br = html[first_br:last_br]
中的文本text_inside_br現在應該是'<b>This</b>\n" is "\n<b>a</b>\n" test "\n<b>string'. 您現在可以清理它,例如通過附加</br>回它并使用 BeautifulSoup 提取值或僅使用正則表達式來執行此操作。
添加回答
舉報