【问题标题】:Why is Beautifulsoup find_all not returning complete results?为什么 Beautifulsoup find_all 没有返回完整的结果?
【发布时间】:2017-06-07 10:12:12
【问题描述】:

我正在尝试解析亚马逊搜索结果页面。我想使用<id=result_0><id=result_1><id=result_2> 等访问<li> 标记中包含的数据。find_all('li') 函数只返回 4 个结果(直到 result_3),我认为这很奇怪,因为在浏览器中查看网页时,我看到了 12 个结果。

当我打印parsed_html 时,我看到它一直包含到 result_23。为什么 find_all 不返回所有 24 个对象?下面是我的代码的 sn-p。

import requests

try: 
    from BeautifulSoup import bsoup
except ImportError:
    from bs4 import BeautifulSoup as bsoup

search_url = 'https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-
              alias%3Dstripbooks&field-keywords=data+analytics'
response = requests.get(search_url, headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
        (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"})
parsed_html = bsoup(response.text)
results_tags = parsed_html.find_all('div',attrs={'id':'atfResults'})
results_html = bsoup(str(results_tags[0]))
results_html.find_all('li')

不管怎样,results_tags 对象也只包含 4 个结果。这就是为什么我认为问题出在find_all 步骤,而不是 BeautifulSoup 对象。

如果有人能帮我弄清楚这里发生了什么以及如何访问此网页上的所有搜索结果,我将不胜感激!

【问题讨论】:

    标签: beautifulsoup


    【解决方案1】:
    import requests, re
    
    try: 
        from BeautifulSoup import bsoup
    except ImportError:
        from bs4 import BeautifulSoup as bsoup
    
    search_url = 'https://www.amazon.com/s/?url=search-%20alias%3Dstripbooks&field-keywords=data+analytics' #delete the irrelevant part from url
    response = requests.get(search_url, headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
            "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" })  # add 'Accept' header
    parsed_html = bsoup(response.text, 'lxml')
    lis = parsed_html.find_all('li', class_='s-result-item' ) # use class to find li tag
    len(lis)
    

    出来:

    25
    

    【讨论】:

    • 啊,我明白了...我不知道 class="s-result-item celwidget" 可以在没有 'celwidget' 的情况下使用 class_='s-result-item' 访问。感谢您的帮助!
    【解决方案2】:

    可以直接通过class而不是id来访问li元素。这将打印每个 li 元素的文本。

    results_tags = parsed_html.find_all('li',attrs={'class':'s-result-item'})
    for r in results_tags:
        print(r.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 2020-02-17
      • 2020-07-13
      • 2018-11-24
      • 2019-03-12
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多