【发布时间】:2022-02-04 05:59:17
【问题描述】:
我正在使用漂亮的汤抓取 H&M 网页,并尝试将 javascript 转换为字符串,然后从中提取服装尺码信息。我认为首先我需要获取字符串,然后我应该拆分字符串并提取我正在寻找的部分,最后我可以使用json.load() 将字符串转换为字典,以便我可以从中获取值字典。但是当我尝试从冗长而凌乱的字符串中提取部分时遇到了问题。此外,由于脚本混合了'' 和"",我也无法直接使用json.load() 加载它们。谁能帮我弄清楚如何提取我正在寻找的部分?
我正在抓取的网页是:https://www2.hm.com/en_us/productpage.0624684003.html。
这就是我找到脚本标签并将其转换为字符串的方式:
user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.90 Safari/537.36'
url='https://www2.hm.com/en_us/productpage.0931364012.html'
headers = {'accept':'*/*',"user-agent":user_agent}
response = requests.get(url,headers=headers)
page = BeautifulSoup(response.content, "html.parser")
script = page.find('div', class_="product parbase").find('script').string
# This is how I find the first level of dictionary:
firstlevel_dict = script.split('productArticleDetails = ')[1]
# in the next step, I hope to convert the above string-like dictionary into a real dictionary, and then find the all displayed sizes for this t-shirt
我附上了一个屏幕截图,显示了 HTML 如下所示,红色框中的内容是我正在寻找的内容。最后,我希望得到一个看起来像['S','M','L','XL','XXL','3XL'] 的尺寸列表。
PS:我也愿意接受其他可能找到 H&M 衣服尺码的方法。谢谢!
PS_plus:我不想在这种情况下使用 Selenium,因为我有成千上万的产品要抓取。 Selenium 在获取我想要的信息时效率太低了。
【问题讨论】:
-
请将有效的python代码上传到帖子中。当前代码无效
-
抱歉,我忘了添加用户代理
-
Python 有
eval()。乍一看,对象格式看起来与 python 的列表和对象格式足够接近,可以正确解析。一旦你可以只提取productArticleDetails的值,你就可以通过eval()运行它并得到一个python 数据结构。
标签: python html json web-scraping python-requests