【发布时间】:2019-06-30 19:51:03
【问题描述】:
我确信我已经编写了一些相当有问题的代码,但它似乎可以完成这项工作。问题是它正在将数据打印到电子表格和列中,如果广告中的第一个词不是年份,那么我希望在该列中找到车辆的年份,然后它会显示第一个可能是制造商的词。
基本上我想设置 if 语句,以便如果车辆年份不在第一个单词中,而是在字符串中的其他位置,它仍然可以找到它并将其打印到我的 .csv 中。
另外,我一直在努力解析多个页面,并希望这里的人也能提供帮助。 url 中有 page=2 等,但我无法让它解析所有 url 并获取所有页面上的数据。目前我所尝试的一切都只做第一页。您可能已经猜到了,我对 Python 还很陌生。
import csv ; import requests
from bs4 import BeautifulSoup
outfile = open('carandclassic-new.csv','w', newline='', encoding='utf-8')
writer = csv.writer(outfile)
writer.writerow(["Link", "Title", "Year", "Make", "Model", "Variant", "Image"])
url = 'https://www.carandclassic.co.uk/cat/3/?page=2'
get_url = requests.get(url)
get_text = get_url.text
soup = BeautifulSoup(get_text, 'html.parser')
car_link = soup.find_all('div', 'titleAndText', 'image')
for div in car_link:
links = div.findAll('a')
for a in links:
link = ("https://www.carandclassic.co.uk" + a['href'])
title = (a.text.strip())
year = (title.split(' ', 1)[0])
make = (title.split(' ', 2)[1])
model = (title.split(' ', 3)[2])
date = "\d"
for line in title:
yom = title.split()
if yom[0] == "\d":
yom[0] = (title.split(' ', 1)[0])
else:
yom = title.date
writer.writerow([link, title, year, make, model])
print(link, title, year, make, model)
outfile.close()
请有人帮我解决这个问题吗?我意识到底部的 if 语句可能会有所偏差。
代码成功地从字符串中获取了第一个单词,遗憾的是数据的结构方式并不总是车辆的制造年份 (yom)
【问题讨论】:
-
这是一个更广泛的问题。
soup.find_all('div', 'titleAndText', 'image')在您的代码中获取不一致的数据类型
标签: python python-3.x beautifulsoup screen-scraping