【发布时间】:2021-07-06 23:57:48
【问题描述】:
您好,我是网页抓取的新手,想用 beautifulsoop 抓取一个网站。现在我想知道 关于如何编写高效的代码。这是关于一个自行车网站,他们有几辆自行车,每辆自行车都有价格、状态、距离和持续时间的功能。他们都有相同的“产品壮举”。将所有这些功能放入 pandas 数据框的最有效方法是什么?我特别问是因为所有功能都具有相同的类,并且循环对我来说似乎效率低下。
<div class="product-smalltext">
<p class="product-feat">
<span>GBP 6'900 <small>(changeable)</small></span><br/> price
</p>
<p class="product-feat">
<span>new</span><br/> state
</p>
<p class="product-feat">
<span>10'000 km</span><br/> distance
</p>
<p class="product-feat">
<span>48 months</span><br/> duration
</p>
我用一个字典(之后我将转换为一个数据框)和一个双循环来完成它,见下文。但这真的是 最有效的方法是什么?使用循环和附加/扩展?还是有更好的办法?
#empty dictionary
content={'price':[],
'state':[],
'distance':[],
'duration':[]
}
listing_content = soup.find_all("div",{"class":"product-smalltext"})
#double loop through all bikes and features
for smalltext in listing_content:
for feat in smalltext.find_all("p",{"class":"product-feat"}):
content['price'].extend(re.findall(r'(?s)^.*?(?=\s*price)', feat.get_text().strip().replace('\xa0',' ')))
content['state'].extend(re.findall(r'(?s)^.*?(?=\s*state)', feat.getText().strip()))
content['distance'].extend(re.findall(r'(?s)^.*?(?=\s*distance)', feat.getText().strip()))
content['duration'].extend(re.findall(r'(?s)^.*?(?=\s*duration)', feat.getText().strip()))
【问题讨论】:
标签: python html pandas web-scraping beautifulsoup