【发布时间】: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