【问题标题】:Python BeautifulSoup problem with extractPython BeautifulSoup 提取问题
【发布时间】:2020-05-08 01:13:02
【问题描述】:
我想提取一些数据并放在excel中。
我的问题在于提取,我没有获取比元素检查看到的所有信息。通过元素检查,我可以看到每个元素、品牌、公里、价格等......所有这些信息都在我的摘录中,但在脚本中,而不像我在网站上看到的那样。
提取网址:https://www.alcopa-auction.fr/salle-de-vente-encheres/nancy/2110
import requests
from bs4 import BeautifulSoup
URL = 'https://www.alcopa-auction.fr/salle-de-vente-encheres/nancy/2110'
page = requests.get(URL)
headers = {"User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15'}
page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
print(soup)
【问题讨论】:
标签:
python
beautifulsoup
request
python-requests
extract
【解决方案1】:
您在页面上看到的数据以 JSON 格式嵌入到页面中。例如,您可以像这样提取它:
import re
import json
import requests
url = 'https://www.alcopa-auction.fr/salle-de-vente-encheres/nancy/2110'
txt = requests.get(url).text
json_string = re.search(r'window.Alcopa.searchResultsJSONString = \'(.*)\';', txt)[1]
data = json.loads( json.loads('"{}"'.format(json_string)) )
# print(json.dumps(data, indent=4)) # <-- uncomment this to see all data
print('{:<20} {:<70} {:<10} {:<10} {:<10}'.format('Brand', 'Model', 'Price', 'Sale Date', 'Sale End Date'))
for car in data['car']:
print('{:<20} {:<70} {:<10} {:<10} {:<10}'.format(car['brand'], car['detailed_model'], car['price'], car['sale_date'], car['sale_end_date']))
打印:
Brand Model Price Sale Date Sale End Date
RENAULT TRAFIC L2H1 1200 1.9 DCI 80 PACK CLIM 2 900 € 22/01/2020 22/01/2020
FIAT DUCATO COMBI 3.3 M H2 2.2 MULTIJET 7 000 € 22/01/2020 22/01/2020
CITROEN C3 HDI 70 CONFORT 3 800 € 22/01/2020 22/01/2020
DS DS3 HDI 90 FAP AIRDREAM SO CHIC 4 000 € 22/01/2020 22/01/2020
VOLKSWAGEN POLO 1.6 TDI 90 CR FAP CONFORTLINE 3 200 € 22/01/2020 22/01/2020
PEUGEOT 207 1.6 HDI 90CH BLUE LION ACTIVE 3 100 € 22/01/2020 22/01/2020
FIAT PANDA MY 1.2 8V 69 CH TEAM 1 600 € 22/01/2020 22/01/2020
FORD KUGA 2.0 TDCI 140 DPF 4X4 TITANIUM POWERSHIFT A 5 400 € 22/01/2020 22/01/2020
... and so on.