【发布时间】:2019-08-08 14:20:09
【问题描述】:
我正在尝试抓取另一个法国网站,我的脚本运行良好,但看起来很丑陋,我认为有更好的方法来实现和抓取我想要的东西。
实际上我使用“item”作为列表并选择所需的每个元素,我想知道是否可以解析这样的选定元素。
for item in soup.select('.search-list-item'):
if '/annonces/' in item.select( 'div.col-right > a'):
print('Ok, my code it's not beautiful but it's better :D')
使用这样的代码,我认为让其他开发人员了解我想要做什么会更好。
实际上是我的脚本:
import requests
from bs4 import BeautifulSoup
import json
url = 'https://www.pap.fr/annonce/vente-maisons-nantes-44-g43619-jusqu-a-900000-euros'
headers = {
'User-Agent': '*',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
}
s = requests.Session()
s.headers.update(headers)
r = s.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
a = []
for item in soup.select('.search-list-item'):
dict = {}
try:
if '/annonces/' in item.contents[3].contents[3].attrs['href']:
dict['id'] = int(item.contents[3].contents[3].attrs['name'])
dict['url'] = "https://www.pap.fr"+item.contents[3].contents[3].attrs['href']
dict['name'] = item.contents[3].contents[3].contents[1].contents[0]
dict['pieces'] = int(''.join(filter(str.isdigit, (item.contents[3].contents[3].contents[3].contents[1].contents[0]))))
dict['chambres'] = int(''.join(filter(str.isdigit, (item.contents[3].contents[3].contents[3].contents[3].contents[0]))))
dict['superficie'] = int(''.join(filter(str.isdigit, (item.contents[3].contents[3].contents[3].contents[5].contents[0]))))
dict['price']= int(''.join(filter(str.isdigit, (item.contents[3].contents[3].contents[5].contents[0]))))
dict['picture']=item.contents[1].contents[1].contents[1].attrs['src']
if dict:
a.append(dict)
except KeyError:
pass
print(json.dumps(a, indent=4))
最后,我的 Json 中出现了一点格式问题,“nbsp;”,我认为这只是 span 中的空格。
非常感谢。
【问题讨论】:
-
可能更适合Code Review。
标签: json python-3.x web-scraping beautifulsoup