[英]Remove unwanted characters from string with BeautifulSoup Python when selecting words from string
我是Python的新手,但仍然不了解所有內容及其功能,但是我已經接近要達到的目標。
從本質上講,我有程序可以從網站上抓取我想要的數據,但是當它從“ specs”字符串中打印選定的單詞/項目時,它也在從字符串中打印諸如[]和”之類的字符。
這個例子是我試圖從li的列表中獲取“ gearbox”類型,“ fuel”類型和“ mileage”,我已經用植物將其轉換為字符串,然后從該字符串中選擇特定項目。
我在當前程序中得到的是:
['Manual'] ['Petrol'] ['86,863 miles']
我想要實現的是這樣的打印結果:
手動,汽油,86,863英里
將其導出到.csv中的單獨列時,應在相應標題下的正確列中顯示。
我試過.text只刪除文本,但是顯示出來的'list'對象沒有屬性'text'錯誤。
import csv
import requests
from bs4 import BeautifulSoup
outfile = open('pistonheads.csv','w', newline='')
writer = csv.writer(outfile)
writer.writerow(["Link", "Make", "Model", "Price", "Image Link",
"Gearbox", "Fuel", "Mileage"])
url = 'https://www.pistonheads.com/classifieds?Category=used- cars&Page=1&ResultsPerPage=100'
get_url = requests.get(url)
get_text = get_url.text
soup = BeautifulSoup(get_text, 'html.parser')
car_link = soup.find_all('div', 'listing-headline', 'price')
for div in car_link:
links = div.findAll('a')
for a in links:
link = ("https://www.pistonheads.com" + a['href'])
make = (a['href'].split('/')[-4])
model = (a['href'].split('/')[-3])
price = a.find('span').text.rstrip()
image_link = a.parent.parent.find('img')['src']
image = ("https:") + image_link
vehicle_details = a.parent.parent.find('ul', class_='specs')
specs = list(vehicle_details.stripped_strings)
gearbox = specs[3:]
fuel = specs[1:2]
mileage = specs[0:1]
writer.writerow([link, make, model, price, image, gearbox, fuel, mileage])
print(link, make, model, price, image, gearbox, fuel, mileage)
outfile.close()
歡迎來到StackOverflow!
因此,您的腳本有很多改進之處。 你到了那里!
specs = list(vehicle_details.stripped_strings)
是解析為列表的生成器。 有效地,您可以通過索引訪問所需的內容。 例如, mileage
可以簡單地是specs[0]
。 [
和]
是由您使用切片mileage = specs[0:1]
。 從文檔中索引將返回一個項目,切片將返回一個新列表 。 請參閱清單簡介 。 mileage, fuel, _, gearbox = specs
mileage = specs[0]
import pdb; pdb.set_trace() # temp set on one line so you can remove it easily after
# now you can interactively inspect your code
(Pdb) specs
祝好運! 享受Python!
如果您想從列表中獲取字符串,也許可以這樣做
gearbox = specs[3:][0] if specs[3:] else '-'
fuel = specs[1:2][0] if specs[1:2] else '-'
mileage = specs[0:1][0] if specs[0:1] else '-'
但是這種方式或aldnav的答案甚至會給出錯誤的結果甚至拋出錯誤
ValueError:沒有足夠的值可解壓縮
通常我會先提取父容器,而不是選擇子容器( a
),然后再選擇父容器。
# helper to get dynamic specs element
def getSpec(element, selector):
spec = element.select_one(selector)
return spec.nextSibling.string.strip() if spec else '-'
soup = BeautifulSoup(get_text, 'html.parser')
results = soup.find_all('div', class_="result-contain")
for car in results:
a = car.find('a')
if not a:
continue
link = ("https://www.pistonheads.com" + a['href'])
make = (a['href'].split('/')[-4])
model = (a['href'].split('/')[-3])
price = a.find('span').text.rstrip()
image_link = car.find('img')['src']
image = ("https:") + image_link
if not car.find('ul', class_='specs'):
gearbox = fuel = mileage = '-'
else:
gearbox = getSpec(car, '.location-pin-4')
fuel = getSpec(car, '.gas-1')
mileage = getSpec(car, '.gauge-1')
print(gearbox, fuel, mileage)
writer.writerow([link, make, model, price, image, gearbox, fuel, mileage])
#print(link, make, model, price, image, gearbox, fuel, mileage)
outfile.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.