首页 > 解决方案 > Python:帮助解析网站并将数据提取到 csv 文件中

问题描述

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

我的 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!

杰克

标签: pythonlistbeautifulsoup

解决方案


[编辑] 获取 horaire 的所有条目:

你可以试试这个:

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]) 

推荐阅读