【问题标题】:How can I scrape supermarket nutrient data with Python's requests?如何使用 Python 的请求抓取超市营养数据?
【发布时间】:2018-02-27 17:56:16
【问题描述】:

我想从这个页面抓取营养数据:http://www.mysupermarket.co.uk/tesco-price-comparison/Fruit/Tesco_Gala_Apple_Approx_160g.html

我尝试了以下代码。

import requests, bs4
res = requests.get('http://www.mysupermarket.co.uk/tesco-price-comparison/Fruit/Tesco_Gala_Apple_Approx_160g.html')

但是响应的文本与我使用浏览器检查页面时看到的 HTML 不匹配。

所以我不能用 Beautiful Soup 来搜索它。

我该如何解决这个问题?

【问题讨论】:

    标签: python web-scraping python-requests


    【解决方案1】:

    一个不错的选择是使用请求的同一作者新发布的 requests-HTML 库。

    这样你就可以像这样简单地解析 HTML:

    from requests_html import HTMLSession
    session = HTMLSession()
    
    r = session.get('https://python.org/')
    sel = 'body > div.application-main > div.jumbotron.jumbotron-codelines > div > div > div.col-md-7.text-center.text-md-left > p'
    
    print(r.html.find(sel, first=True).text)
    

    通过official site查看。

    谢谢。

    【讨论】:

      【解决方案2】:

      您需要从res 对象的.text 属性中检索标记。然后您的代码应为:

      import requests, bs4
      res = requests.get('http://www.mysupermarket.co.uk/tesco-price-comparison/Fruit/Tesco_Gala_Apple_Approx_160g.html')
      html = res.text
      

      【讨论】:

        【解决方案3】:

        这是由于在不同浏览器上查看时 html 标签的方向不同而引起的问题。这是由于每个浏览器的用户代理不同。

        如果您想在浏览器中看到相同的文本,请使用 Selenium Webdriver。 它使用起来非常简单方便。 完成后获取源代码并在其上使用 Beautiful Soup。

        如果您想了解如何实现 selenium,请查看 here

        即使遇到问题也可以随时联系。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-31
          • 1970-01-01
          • 1970-01-01
          • 2016-07-03
          • 1970-01-01
          相关资源
          最近更新 更多