Python:帮助解析网站并将数据提取到csv文件中

时间:2020-06-23 17:40:23

标签: python list beautifulsoup

这是我在这里的第一个问题,请随时告诉我我做错了什么。 我正在尝试从电影网站中提取“标题”和“放映时间”以进行社会学研究。

我的python代码正在运行,但是当我想将它们全部包含在csv文件中时,它仅占用列表中名为“ horaire”的第一个索引。

我的问题是我不知道此列表将包含多少索引。

在下面找到我的脚本:

from urllib import urlopen
from bs4 import BeautifulSoup
import csv
import sys

url = "http://www.allocine.fr/seance/salle_gen_csalle=C0116.html"
html = urlopen(url).read()
soup = BeautifulSoup(html, "lxml")
reload(sys)
sys.setdefaultencoding('utf8')

with open('test2306.csv', 'wb') as csvfile:
    cinemaWriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

    for films in soup.find_all('div',
                               {'class': 'card entity-card entity-card-list movie-card-theater cf hred'}):
        horaire = films.find_all('span',
                               {'class': 'showtimes-hour-item-value'})
        titres = films.find_all('a',
                               {'class': 'meta-title-link'})
        cinemaWriter.writerow([horaire[0:].text.strip(),
                                titres[0:].text.strip()]) 

谢谢您的帮助<3!

杰克

1 个答案:

答案 0 :(得分:1)

[编辑]获取恐怖片的所有条目:

您可以尝试以下方法:

with open('test2306.csv', 'w') as csvfile:  ## 'w' instead of 'wb'
    cinemaWriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

    for films in soup.find_all('div',
                               {'class': 'card entity-card entity-card-list movie-card-theater cf hred'}):
        horaire = films.find_all('span',
                               {'class': 'showtimes-hour-item-value'})
        titres = films.find_all('a',
                               {'class': 'meta-title-link'})
        
        horaire = ','.join([i.text for i in horaire])

        cinemaWriter.writerow([horaire, titres[0].text])