【问题标题】:Scraping <script> tag with BS4用 BS4 抓取 <script> 标签
【发布时间】:2017-09-20 20:10:28
【问题描述】:

我是 Python 新手,正在尝试开发一个简单的网络爬虫。我在抓取 HTML 中的脚本标签时遇到问题。这是我的代码:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import re

link = "https://yeezysupply.com/products/womens-mule-pvc-clear"

def get_variants():
    url1 = Request(link, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36'
                '(KHTML, like Gecko) Chrome/56.0.2924.28 Safari/537.36'})
    url2 = urlopen(url1)
    soup = BeautifulSoup(url2, 'html.parser')
    variants = soup.find(string=re.compile(r'\bid\s*:\s(\d{11}),\s*parent_id'))
    print(variants)

if __name__ == '__main__':
    get_variants()

当前返回的代码:

KANYE.p.variants.push({
  id                : 38844706759,
  parent_id         : 9876888199,
  available         : true,
  featured_image    : null,
  public_title      : null,
  requires_shipping : true,
  price             : 62500,
  options           : ["35"],
  option1           : "35",
  option2           : "",
  option3           : "",
  option4           : ""
});

KANYE.p.variants.push({
  id                : 38844706887,
  parent_id         : 9876888199,
  available         : true,
  featured_image    : "\/\/cdn.shopify.com\/s\/files\/1\/1765\/5971\/products\/KW3029.001_Side1_650xx.jpg?v=1488326253",
  public_title      : null,
  requires_shipping : true,
  price             : 62500,
  options           : ["35.5"],
  option1           : "35.5",
  option2           : "",
  option3           : "",
  option4           : ""
});

KANYE.p.variants.push({
  id                : 38844706951,
  parent_id         : 9876888199,
  available         : true,
  featured_image    : null,
  public_title      : null,
  requires_shipping : true,
  price             : 62500,
  options           : ["36"],
  option1           : "36",
  option2           : "",
  option3           : "",
  option4           : ""
});
...

我试图只抓取“id”及其值。所以我需要刮 id: 38844706759, id: 38844706887, id: 38844706951。这怎么可能?我在这方面已经有一段时间了,我仍然很困惑。

【问题讨论】:

    标签: python python-3.x beautifulsoup bs4


    【解决方案1】:

    BeautifulSoup 无法解析脚本标签。只在其中找到与您的查询匹配的文本(因为它们是顶级元素的一部分。)。

    variants = soup.find(string=re.compile(r'\bid\s*:\s(\d{11}),\s*parent_id')) 之后,您可以执行正则表达式 findall 来查找 ID 标签。

    variants = soup.find_all(string=re.compile(r'\bid\s*:\s(\d{11}),\s*parent_id'))
    for variant in variants:
        print (re.findall(r'id\s+:.(.*?),', variant,  re.MULTILINE))
    

    哪些输出

    [u'9876888199', u'38844706759', u'9876888199'...]
    

    【讨论】:

    • 啊,我明白了,谢谢您的回复。我试图实现该代码,它无数次返回[] 而不是id。我哪里错了?
    • @BrianHunt 使用我更新帖子的代码更新您的变体查找;
    • 谢谢,效果很好。有没有办法只输出 id 而不是 parent_id?
    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2020-09-30
    • 2020-10-19
    • 2011-07-16
    • 2021-02-19
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多