Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 从 a> 抓取一系列链接(在其他两个标签之间)

2025年05月04日13soundcode

请你帮我解决一个基于这段 html 代码的 Python 问题:

<h2 class="sectionTitle">One</h2> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1230559">Text1</a></div> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1648920">Text2</a></div> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1207230">Text3</a></div><div> 
<h2 class="sectionTitle">Two</h2> 

我正在尝试获取字符串(Text1、Text2 ...)以及两个 h2 之间的 href 链接标签。

通过跳转到 h2 可以很好地捕获字符串标记(带有字符串 =“一个”),然后遍历 sibling 直到到达下一个 h2节点同时捕获途中的一切。

page = urllib.request.urlopen(url) 
soup = BeautifulSoup(page, "lxml") 
 
education = [] 
edu = soup.find("h2", string="One") 
for elt in edu.nextSiblingGenerator(): 
    if elt.name == "h2": 
        break 
    if hasattr(elt, "text"): 
        education.append(elt.text + "\n") 
print("".join(education)) 

我无法复制它以从 <a> 收集链接- 在附加列表中标记。我很业余地尝试像 education2.append(elt2.get("href")) 这样的东西,但收效甚微。有什么想法吗?

谢谢!!

请您参考如下方法:

你非常接近做你想做的事。我做了一些更改。

这会给出你想要的:

html = '''<h2 class="sectionTitle">One</h2> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1230559">Text1</a></div> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1648920">Text2</a></div> 
<div><a itemprop="affiliation" href="../../snapshot.asp?carId=1207230">Text3</a></div> 
<div>dummy</div> 
<h2 class="sectionTitle">Two</h2>''' 
 
soup = BeautifulSoup(html, 'lxml') 
texts = [] 
links = [] 
for tag in soup.find('h2', text='One').find_next_siblings(): 
    if tag.name == 'h2': 
        break 
    a = tag.find('a', itemprop='affiliation', href=True, text=True) 
    if a: 
        texts.append(a.text) 
        links.append(a['href']) 
 
print(texts, links, sep='\n') 

输出:

['Text1', 'Text2', 'Text3'] 
['../../snapshot.asp?carId=1230559', '../../snapshot.asp?carId=1648920', '../../snapshot.asp?carId=1207230'] 

我添加了一个虚拟 <div>没有子标签的标签,以表明代码在任何其他情况下都不会失败。


如果 HTML 没有任何 <a>带有 itemprop="affiliation" 的标签除了你想要的,你可以直接使用这个:

texts = [x.text for x in soup.find_all('a', itemprop='affiliation', text=True)] 
links = [x['href'] for x in soup.find_all('a', itemprop='affiliation', href=True)]