我正在尝试从网站上抓取文本,但特别是仅抓取与两个特定链接之一链接的文本,然后另外抓取紧随其后的另一个文本字符串。
第二个文本字符串很容易抓取,因为它包含一个我可以定位的独特类,所以我已经开始工作了,但我无法成功抓取第一个文本(使用两个特定的链接)。
我发现了这个 SO 问题 ( Find specific link w/ beautifulsoup ) 并尝试实现它的变体,但无法让它工作。
这是我试图抓取的 HTML 代码片段。这种模式在我抓取的每一页的过程中反复出现:
<em>[<a href="forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=19">女孩</a>]</em> <a href="thread-443414-1-1.html" onclick="atarget(this)" class="s xst">寻找2003年出生2004年失踪贵州省黔西南布依族苗族自治州贞丰县珉谷镇锅底冲 黄冬冬289179</a>
我试图抓取然后一起存储在列表中的两个部分是两个中文文本字符串。
第一个,女孩,意思是女性,是我没能成功抓到的。
这总是在这两个链接之一之前:
forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=19
(女)
forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=15
(男)
我测试了很多不同的东西,包括:
gender_containers = soup.find_all('a', href = 'forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=19')
print(gender_containers.get_text())
但是对于我所尝试的一切,我不断收到如下错误:
ResultSet object has no attribute 'get_text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
我认为我没有成功找到那些链接来抓取文本,但到目前为止,我的基本 Python 技能使我无法弄清楚如何实现它。
我最终想要发生的是抓取每个页面,使得这段代码中的两个字符串(女孩
和寻找2003年出生2004年失足贵州省...
)
<em>[<a href="forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=19">女孩</a>]</em> <a href="thread-443414-1-1.html" onclick="atarget(this)" class="s xst">寻找2003年出生2004年失踪贵州省黔西南布依族苗族自治州贞丰县珉谷镇锅底冲 黄冬冬289179</a>
...被抓取为两个单独的变量,以便我可以将它们存储为列表中的两个项目,然后向下迭代到此代码的下一个实例,抓取这两个文本片段并将它们存储为另一个列表,等等。我正在构建一个列表列表,其中我希望每行/嵌套列表包含两个字符串:性别(女孩或男孩),然后是更长的字符串,它有更多的变化。
(但目前我有可以抓取和存储它的工作代码,我只是无法让性别部分工作。)
最佳答案
听起来你可以使用 attribute = value css 选择器,$ 以运算符结尾
如果每页只能出现一次
soup.select_one("[href$='typeid=19'], [href$='typeid=15']").text
这是假设那些 typeid=19
或 typeid=15
只出现在感兴趣的字符串的末尾。选择器中两者之间的“,”是为了允许匹配其中任何一个。
您还可以按如下方式处理不在场的可能性:
from bs4 import BeautifulSoup
html ='''<em>[<a href="forum.php?mod=forumdisplay&fid=191&filter=typeid&typeid=19">女孩</a>]</em> <a href="thread-443414-1-1.html" onclick="atarget(this)" class="s xst">寻找2003年出生2004年失踪贵州省黔西南布依族苗族自治州贞丰县珉谷镇锅底冲 黄冬冬289179</a>'''
soup=BeautifulSoup(html,'html.parser')
gender = soup.select_one("[href$='typeid=19'], [href$='typeid=15']").text if soup.select_one("[href$='typeid=19'], [href$='typeid=15']") is not None else 'Not found'
print(gender)
多个值:
genders = [item.text for item in soup.select_one("[href$='typeid=19'], [href$='typeid=15']")]
关于html - 如何根据 BeautifulSoup 的特定链接抓取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987683/