1. 程式人生 > >scrapt中的數據提取,采用js2xml庫

scrapt中的數據提取,采用js2xml庫

方法 per cto scrip 發送 rap lec 取數據 ring

這個一個爬去美團的例子,應為數據都是在script中,小心封ip,盡量少運行。

先導入庫幾個庫

import requests
from bs4 import BeautifulSoup
from lxml import etree
import js2xml

發送請求,獲取到script裏面的數據

url = "https://sz.meituan.com/meishi/"
headers = {}
response = requests.get(url, headers = headers)
content = response.text
bs = BeautifulSoup(content, "
lxml") l = bs.select("body script")[13].string #獲取到body中第十三個script裏面的數據

然後在利用js2xml方法格式化之後再利用xpath來提取數據

src_text = js2xml.parse(l, encoding=utf-8, debug=False)
print(type(src_text))
src_tree = js2xml.pretty_print(src_text)
print(src_tree)
selector = etree.HTML(src_tree)
content = selector.xpath(
//property[@name="poiId"]/number/@value) name = selector.xpath(//property[@name="title"]/string/text())

就ok了

scrapt中的數據提取,采用js2xml庫