python - 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!
杰克
解决方案
[编辑] 获取 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])
推荐阅读
- java - 我将如何使用 Java 技术将图书馆管理系统开发为 Web 应用程序
- javascript - 初始化 jquery 插件时设置 scrollTop
- ehcache - 如何使用 EhCache3 在 Spring Boot 2 中从外部位置加载 ehCache.xml
- angular - 模块“ComponentsModule”声明的意外值“DecoratorFactory”
- python-3.x - 当在图像中找不到对象时,如何使 keras 模型在进行预测时不返回任何结果?
- osmnx - 是否有 OSMnx 函数来查找距地理编码地址最近的建筑物占地面积?
- c++ - 使用 sscanf 设置结构引用的值
- c# - C#多线程foreach循环
- php - 从另一个 PHP 文件访问变量
- java - 如何修复使用名称创建 bean 的错误?