Skip to main content
 首页 » 编程设计

Python 3,漂亮的汤,获取下一个标签

2024年11月01日7xing901022

我有以下 html 部分,它与其他 href 链接重复多次:

<div class="product-list-item  margin-bottom"> 
<a title="titleexample" href="http://www.urlexample.com/example_1" data-style-id="sp_2866"> 

现在我想获取本文档中紧跟在类“product-list-item”的div 标签之后的所有href 链接。 beautifulsoup 很新,我想出的任何东西都没有用。

感谢您的想法。

编辑:不一定要是 beautifulsoup;当可以使用正则表达式和 python html 解析器完成时,这也可以。

EDIT2:我尝试了什么(我对 python 很陌生,所以从高级的角度来看我所做的可能是完全愚蠢的):

soup = bs4.BeautifulSoup(htmlsource) 
x = soup.find_all("div") 
for i in range(len(x)): 
    if x[i].get("class") and "product-list-item" in x[i].get("class"): 
        print(x[i].get("class")) 

这会给我一个所有“产品列表项”的列表,但后来我尝试了类似的东西

print(x[i].get("class").next_element) 

因为我认为 next_element 或 next_sibling 应该给我下一个标签,但它只会导致 AttributeError: 'list' object has no attribute 'next_element'。所以我只尝试了第一个列表元素:

print(x[i][0].get("class").next_element) 

这导致了这个错误:return self.attrs[key] KeyError: 0。 还尝试使用 .find_all("href") 和 .get("href") 但这都会导致相同的错误。

EDIT3:好的,看来我找到了解决方法,现在我做到了:

x = soup.find_all("div") 
 
for i in range(len(x)):     
    if x[i].get("class") and "product-list-item" in x[i].get("class"): 
        print(x[i].next_element.next_element.get("href")) 

这也可以通过对 find_all 函数使用另一个属性来缩短:

x = soup.find_all("div", "product-list-item") 
for i in x: 
    print(i.next_element.next_element.get("href")) 

问候

请您参考如下方法:

I want to get all the href links in this document that are directly after the div tag with the class "product-list-item"

找到第一个<a href> <div> 中的元素:

links = [] 
for div in soup.find_all('div', 'product-list-item'):  
    a = div.find('a', href=True) # find <a> anywhere in <div> 
    if a is not None: 
       links.append(a['href']) 

它假定链接在<div> 内. <div> 中的任何元素在第一个之前 <a href>被忽略。

如果你愿意;你可以更严格一点,例如,只有当它是 <div> 中的第一个 child 时才使用链接。 :

a = div.contents[0] # take the very first child even if it is not a Tag 
if a.name == 'a' and a.has_attr('href'): 
   links.append(a['href']) 

或者如果 <a>不在里面<div> :

a = div.find_next('a', href=True) # find <a> that appears after <div> 
if a is not None: 
   links.append(a['href']) 

There are many ways to search and navigate in BeautifulSoup .

如果您使用 lxml.html 进行搜索,如果您熟悉 xpath 和 css 表达式,也可以使用它们。