【问题标题】:Python3, Beautifulsoup4 tag confusionPython3、Beautifulsoup4标签混淆
【发布时间】:2017-01-23 07:41:03
【问题描述】:

我正在尝试从亚马逊获取一些数据,我的代码是:

import requests, bs4

source_code = requests.get("https://www.amazon.com/s/ref=sr_nr_p_n_feature_keywords_0?fst=as%3Aoff&rh=n%3A2335752011%2Cn%3A%212335753011%2Cn%3A7072561011%2Cn%3A2407749011%2Cp_89%3AHuawei%2Cp_n_feature_keywords_four_browse-bin%3A6787346011&bbn=2407749011&ie=UTF8&qid=1473923594&rnid=6787345011", 
    headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36"
})
source_code.raise_for_status()

soup = bs4.BeautifulSoup(source_code.text, 'lxml')
mobile_div = soup.find_all("div", class_="a-row a-spacing-small")
for mobile_name in mobile_div:
    print(mobile_name.a.find_next("h2").string)

它输出很好,但是当我使用时

print(mobile_name.a.h2.string)

而不是显示以下错误:

print(mobile_name.a.h2.string)
AttributeError: 'NoneType' object has no attribute 'string'

我的标记是:

谁能解释我为什么会收到这个错误?

【问题讨论】:

    标签: beautifulsoup python-3.5


    【解决方案1】:

    因为返回的第一个锚点是:

    <a class="a-button-text" href="/gp/help/contact-us/general-questions.html/ref=sr_hms_cs/155-8370713-5732665?browse_node_id=468556&amp;ie=UTF8&amp;qid=1473939395" role="button">contact us</a>
    

    它没有 h2 子/后代,调用 find_next 在锚点之后到处寻找 h2 所以即使它没有孩子它会找到下一个。 a.h2 查找锚的子/后代,因此上面的第一个锚返回 None。

    find_all_next() and find_next()

    这些方法使用 .next_elements 来迭代文档中紧随其后的任何标签和字符串。 find_all_next() 方法返回所有匹配,find_next() 只返回第一个匹配:

    这个简单的例子应该

    In [34]: html = """<div>
              <a class="a-button-text" href="/fof.com">foobar</a> 
              <h2 class="sibling"> blah</h2> 
              <div ><h2 class="nexted"> blah</h2></div> 
              </div>"""
    
    In [34]: soup = bs4.BeautifulSoup(html, 'lxml')
    
    In [35]: a = soup.div.a
    In [36]: print(a.h2) # a has no direct descendants so we get None
    None
    In [37]: a.find_next("h2") # finds the next h2 anywhere after the anchor 
    Out[37]: <h2 class="sibling"> blah</h2>
    
    
    In [38]: a.find_next_siblings("h2") # finds any h2's in the tree that are siblings
    Out[38]: [<h2 class="sibling"> blah</h2>]
    
    In [39]: a.find_all_next("h2") # finds all h2s anywhere after 
    Out[39]: [<h2 class="sibling"> blah</h2>, <h2 class="nexted"> blah</h2>]
    

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 2012-11-12
      • 2020-01-22
      • 2020-07-31
      • 2018-11-06
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多