【问题标题】:how can I get specific contents under the "script" tag如何在“脚本”标签下获取特定内容
【发布时间】: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


【解决方案1】:

从你离开你得到的字符串的地方继续不是完全的 JSON 数据格式化文本有

# This is how I find the first level of dictionary:
firstlevel_dict = script.split('productArticleDetails = ')[1]
dictionary_to_get = firstlevel_dict[:firstlevel_dict.rfind(';')] # remove ';' at the end of the string to make it part of a dictionary

dictionary_to_get = dictionary_to_get.replace('\'', '"') # first error -- the text is formatted with single quotes where json needs double
dictionary_to_get = dictionary_to_get.replace('isDesktop ?', '"isDesktop ?",') # second error this word is part of a strange double value (dictionary with a dictionary) didn't know how you would have liked it to format, so did a simple solution to load the dictionary

print(json.loads(dictionary_to_get))

现在您可以遍历字典以获取您的信息,如下所示:

for k,v in json_dictionary.items():
    try:
        int(k)
    except:
        continue
    #print(v['sizes']) # print the size dictionary totally (outside your highlight)
    for item in v['sizes']:
        print(item['name']) # get just the name 

【讨论】:

  • 哇,非常感谢!这太酷了!
  • 但是一个后续问题,你是怎么发现isDesktop ?不被python识别的?希望下次遇到类似问题时也能识别出来
  • @wydncwymsjgcs 将单曲改为双曲后不起作用。然后,我将已更改为 jsonformatter.org 的响应加载到当我尝试验证 json 时,查看未正确格式化的元素(我看到的第一个错误)
  • 太棒了!谢谢安德鲁!
  • 嗨 Andrew,您是否将字符串复制并粘贴到该网站?但是为什么当我粘贴它时,网站总是提醒我 \r\n UNDEFINED 或类似的东西。我可以知道你如何检查字符串的程序吗?谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多