我从一个汽车网站的网页抓取数据,以获得价格。现在,我通过创建两个单独的列表来解决这个问题:一个是定价数据,另一个是车型数据。最后,我想把每个列表和两个一起创建一个CSV。 我为解决这个问题采取的具体步骤如下:
from bs4 import BeautifulSoup
import urllib2
#1) establishing a connection to the website
wiki = "http://www.morong.com/used-inventory/index.htm?start=16&"
req = urllib2.Request(wiki)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page, 'lxml')
#2) creating two empty lists to write the data into
valueHolder = []
nameHolder = []
#3) selecting the correct data from each part of the page
value = soup.findAll("span", { "class" : "value" })
name = soup.findAll("a", {"class" : "url"})
#4) iterates over rows and turns each row into a text field
for row in value:
valueholder = row.text
for row in name:
nameHolder = row.text
print(valueholder)
print(nameHolder)
当我打印valueHolder
和nameHolder
时,我只返回每个for循环的最后一行。如何打印所有值?你知道吗
使用zip()函数连接这两个列表:
也可以创建字典而不是列表
dict_not_list = dict((zip(name, value))
您在循环中分配
valueHolder
和nameHolder
标识符,而不是向列表中添加元素。试试这个:要组合列表,可以使用
map
,例如简单地说:
相关问题 更多 >
编程相关推荐