【问题标题】:The HTML that python requests (and urllib) is not giving the same HTML as the originalpython 请求的 HTML(和 urllib)没有提供与原始 HTML 相同的 HTML
【发布时间】:2020-06-17 23:48:52
【问题描述】:

我正在尝试创建一个“价格比较”python 脚本。我正在使用 '''request''' 和 '''Beautiful Soup''' 来获取价格。

但它没有提供与原始 HTML 相同的 HTML。我试过用headers,也试过用urllib还是不行。

任何帮助都会有所帮助。提前谢谢你

import requests
from bs4 import BeautifulSoup

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"}

response = requests.get("https://www.lazada.com.ph/products/rubiks-cube-i122835501-s127979620.html", headers=headers, timeout=5, allow_redirects=True)

soup = BeautifulSoup(response.content, "lxml")

price = soup.find("span", {"class": "pdp-product-price"})

print(price) #Output is None

【问题讨论】:

  • 嗨,欢迎来到 SO。什么是原始 HTML,你得到了什么?,你做了什么代码?我认为这个问题必须得到改善。否则它可能很容易被关闭。
  • 对不起,我不小心按了 Enter,我已经用原始代码编辑了问题
  • 我认为它是一个动态页面,您正在搜索的类是在正文加载时通过脚本执行自动创建的。可能有一些脚本没有被触发的问题
  • 我了解,您有什么建议或其他方法来获取我需要的 html 吗?

标签: python html python-requests python-requests-html


【解决方案1】:

要获得所需的结果,您可以将selenium webdriverBeautifulSoup 结合使用。

试试这个:

from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome(executable_path="path_to_chromedriver")
driver.get("https://www.lazada.com.ph/products/rubiks-cube-i122835501-s127979620.html")

soup = BeautifulSoup(driver.page_source, "lxml")
price = soup.find("span", {"class": "pdp-price"})

print(price.text) #Outp

输出:

₱1,250.00

【讨论】:

    【解决方案2】:

    你不需要使用selenium 来完成这样的任务,因为它会完全减慢你的工作速度。您可以加载script 源并获取信息。即使您可以在r.text 上使用正则表达式来匹配"salePrice":{"text":"₱1,250.00","value":1250}}

    但是这里有一个非常简单的解决方案,requests

    import requests
    from bs4 import BeautifulSoup
    import json
    
    r = requests.get(
        "https://www.lazada.com.ph/products/rubiks-cube-i122835501-s127979620.html")
    
    soup = BeautifulSoup(r.text, 'html.parser')
    
    script = soup.find("script", type="application/ld+json").text
    
    price = json.loads(script)
    
    print(price["offers"]["price"])
    

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 2022-01-22
      • 1970-01-01
      • 2020-05-05
      相关资源
      最近更新 更多