我是python和beautifulsoup的新手,花了不少时间试图弄清楚这个 .
我想在没有类的 <div>
中提取三个特定的文本提取 .
我想要的第一个文本提取是在 <a>
标记内,该标记位于 <h4>
标记内 . 我设法提取它 .
第二个文本提取紧跟在结束h4标记 </h4>
之后,后跟一个 <br>
标记 .
第二个文本提取紧跟在第二个文本提取后的 <br>
标记之后,后面跟着一个 <br>
标记 .
这里是我使用的html提取:
<div>
<h4 class="actorboxLink">
<a href="/a-decheterie-de-bagnols-2689">Decheterie de Bagnols</a>
</h4>
Route des 4 Vents<br>
63810 Bagnols<br>
</div>
我想提取:
Decheterie de Bagnols <有效
Route des 4 Vents <不起作用
63810 Bagnols <不起作用
这是我到目前为止的代码:
import urllib
from bs4 import BeautifulSoup
data = urllib.urlopen(url).read()
soup = BeautifulSoup(data, "html.parser")
name = soup.findAll("h4", class_="actorboxLink")
for a_tag in name:
print a_tag.text.strip()
我需要像“soup.findAll( </h4>
之后的所有文字)”之类的东西
我使用.next_sibling玩,但我不能让它工作 .
有任何想法吗?谢谢
更新:
我试过这个:
for a_tag in classActorboxLink:
print a_tag.find_all_next(string=True, limit=5)
这给了我:
[u '\n',你'\r\n\t\t\t\t\t\tDecheterie\xa0de\xa0Bagnols\t\t\t\t\t',你'\n',你'\r\n\t\t\t\tRoute\xa0des\xa04\xa0Vents',你'\r\n\t\t\t\t63810 Bagnols']
这是一个开始,但我需要重新获得所有的空白和不必要的角色 . 我尝试使用 .strip()
, .strings
和 .stripped_strings
但它不起作用 . 例子:
for a_tag in classActorboxLink.strings
for a_tag in classActorboxLink.stripped_strings
print a_tag.find_all_next(string=True, limit=5).strip()
对于这三个我得到:
AttributeError: 'ResultSet' object has no attribute 'strings/stripped_strings/strip'
2 回答
找到
h4
元素并使用find_next_siblings():如果你不需要在不同变量中寻找的3个元素中的每个元素,你可以使用
<div>
上的get_text()
函数将它们全部放在一个字符串中 . 如果有其他div
标签,但它们都有类,您可以找到所有<div>
与class=false
. 如果您无法隔离您感兴趣的<div>
,那么此解决方案将不适合您 .顺便说一句,这是python 3&bs4