我有一个列表,listOfActors,它包含了从这个网站上找到的每部电影中演员的子列表-http://www.boxofficemojo.com/yearly/chart/?yr=2013&p=.htm。你知道吗
我让演员们使用网络画图功能
def getActors(item_url):
response = requests.get(item_url)
soup = BeautifulSoup(response.content, "lxml") # or BeautifulSoup(response.content, "html5lib")
tempActors = []
try:
tempActors.append(soup.find(text="Actors:").find_parent("tr").find_all(text=True)[1:])
except AttributeError:
tempActors.append("n/a")
return tempActors
结果是以这种格式列出参与者
[u'Jennifer Lawrence', u'Josh Hutcherson', u'Liam Hemsworth', u'Elizabeth Banks', u'Stanley Tucci', u'Woody Harrelson', u'Philip Seymour Hoffman', u'Jeffrey Wright', u'Jena Malone', u'Amanda Plummer', u'Sam Claflin', u'Donald Sutherland', u'Lenny Kravitz']
[u'Robert Downey, Jr.', u'Gwyneth Paltrow', u'Don Cheadle', u'Guy Pearce', u'Rebecca Hall', u'James Badge Dale', u'Jon Favreau', u'Ben Kingsley', u'Paul Bettany*', u' ', u'(Voice)', u'Mark Ruffalo*', u' ', u'(Cameo)']
我将这些数据导出到一个csv文件中,每个列表都在一个单独的行中。我有两个问题:
首先,如何从每个子列表中删除“u”标记,最好也删除括号?你知道吗
其次,当我打开csv文件时,我希望每个参与者都在excel中自己的块中。现在他们都在一个巨大的街区里。你知道吗
I want the final output to be like:
Jennifer Lawrence |Josh Hutcherson|Liam Hemsworth|... so on and so forth
Robert Downey, Jr. | Gwyneth Paltrow|Don Cheadle|
而不是
[u'Jennifer Lawrence', u'Josh Hutcherson', u'Liam Hemsworth', u'Elizabeth Banks', u'Stanley Tucci', u'Woody Harrelson', u'Philip Seymour Hoffman', u'Jeffrey Wright', u'Jena Malone', u'Amanda Plummer', u'Sam Claflin', u'Donald Sutherland', u'Lenny Kravitz']
[u'Robert Downey, Jr.', u'Gwyneth Paltrow', u'Don Cheadle', u'Guy Pearce', u'Rebecca Hall', u'James Badge Dale', u'Jon Favreau', u'Ben Kingsley', u'Paul Bettany*', u' ', u'(Voice)', u'Mark Ruffalo*', u' ', u'(Cameo)']
这是我的主要webcrawling函数,我在其中调用getActors函数:
def spider(max_pages):
page = 1
while page <= max_pages:
url = 'http://www.boxofficemojo.com/yearly/chart/?page=' + str(page) + '&view=releasedate&view2=domestic&yr=2013&p=.htm'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.select('td > b > font > a[href^=/movies/?]'):
href = 'http://www.boxofficemojo.com' + link.get('href')
listOfActors.append(getActors(href))
page += 1
首先,您应该将getActors的当前实现更改为。当前实现返回一个列表列表。这将返回单个列表。你知道吗
然后,在将
getActors
中的许多列表收集到一个名为listOfActors
的列表列表列表之后,您可以将它们全部写入如下csv文件请使用逗号分隔这些值。另外,python将自动处理unicode字符串。你知道吗
相关问题 更多 >
编程相关推荐