Python美丽的汤网页剪辑:只返回新的数据?
问题描述:
我对Python的webscraping世界很陌生,但我想开发的终极技能是将刮取的数据存储到数据库中并定期刷新数据。Python美丽的汤网页剪辑:只返回新的数据?
我的问题是:如何节省数据请求(时间,带宽使用),只请求自上次运行脚本以来新增的数据?
例如,我的代码返回在网站上Autotrader汽车的上市:
from bs4 import BeautifulSoup
import requests
#URL and headers so it thinks we are a browser
url = "https://www.autotrader.co.uk/car-search?search-target=usedcars&is-quick-search=true&radius=&onesearchad=used&onesearchad=nearlynew&onesearchad=new&make=AC&model=&price-from=&price-to=&postcode=sw65bg"
headers = {'User-Agent' : 'Mozilla/5.0'}
#Request
request = requests.get(url, headers)
soup = BeautifulSoup(request.text, "html.parser")
#Find the name box
name_box = soup.find_all('h2', attrs={'class' : 'listing-title'})
#Print the name_box results to see them
for listing in range(len(name_box)):
temp = name_box[listing]
value = temp.text
print(value)
而不是使用一个数据库的,我可以输出存储在一个数据帧,以帮助说明我的问题:
data = pd.DataFrame(columns=['A'])
#Print the name_box results to see them
for listing in range(len(name_box)):
temp = name_box[listing]
value = temp.text
data = data.append({'A' : value}, ignore_index=True)
,输出:
A
0 AC Cobra 6.3 2dr
1 AC Cobra 4.9 MK IV 2dr
2 AC Cobra 3.5 2dr
3 AC Cobra 3.5 2dr
4 AC Cobra 5.3 2dr
5 AC Cobra 5.7
6 AC Cobra 4736 Built By Gardner Douglas 4.7 2dr
7 AC Cobra 5.7
8 AC Cobra 5.7 2dr
9 AC Cobra 5.8
如果一个10 AC眼镜蛇出现在网站上,是有没有办法显示或附加新条目,以便我可以识别出现的新条目?
答
如果页面发送一个ETag
header(基本上是页面的校验和),您可以将数据库发送到您的下一个请求并发送它。如果没有变化,服务器将发回一个304
(不变),您可以停止。
如果页面发送Last-Modified
header,则可以将其数据库并将其与Last-Modified
标头在下一个请求中进行比较。为了节省处理,在刮削之前检查头部。如果页面很少更改,则可以通过downloading only the header节省带宽。
,或者甚至更好,发送与If-Modified-Since
header的请求,服务器应该返回一个304
或200
(全响应)根据页面是否比你的最后的时间戳更新。
当然,所有这一切都取决于服务器/页面所有者很好通过发送和处理有用的标题。不幸的是,我没有看到您的示例页面附带ETag
或Last-Modified
标头。
最终,确定没有新数据的唯一方法是将其擦除并与数据库中的数据进行比较。您可以通过编写灵活的抓取和DB代码尽可能地优化该过程。