我正试图为一个数据科学项目从BoxOfficeMojo中收集数据。为了满足我的需要,我从一个已经存在的GitHub存储库中对这段代码做了一些修改。
https://github.com/OscarPrediction1/boxOfficeCrawler/blob/master/crawlMovies.py
我需要一些帮助,关于刮一个特定的功能。虽然我可以正常抓拍一部电影,但票房Mojo有一个功能,它向你展示了通胀调整后的总票房(如果电影在任何特定年份上映的话,那就是它的总票房)。通货膨胀调整后的总收入在正常电影链接的末尾有一个额外的"&adjust_yr=2018“。
例如-
泰坦尼克正常链(http://www.boxofficemojo.com/movies/?id=titanic.htm)
泰坦尼克号2018年通货膨胀调整链接(yr=2018)
在我前面链接的特定代码中,通过遍历字母列表(http://www.boxofficemojo.com/movies/alphabetical.htm )创建一个URL表,然后访问每个URL。问题是,字母列表有正常的电影链接,而不是通货膨胀调整后的链接。我该怎么做才能得到通货膨胀调整后的数值呢?
(我唯一能一次抓取所有电影的方法是通过字母列表。我之前已经查过了)
发布于 2018-06-10 01:21:01
一种可能的方法是简单地生成所有必要的url,方法是在普通url列表中添加"&adjust_yr=2018“并对每个站点进行抓取。
我个人喜欢使用xpath (一种用于导航html结构的语言,对于抓取非常有用!)并建议不要使用字符串匹配来过滤来自它曾经被推荐给我的数据。使用xpath的一种简单方法是通过lxml库。
from lxml import html
<your setup>
....
for site in major_sites:
page = 1
while True:
# fetch table
url = "http://www.boxofficemojo.com/movies/alphabetical.htm?letter=" + site + "&p=.htm&page=" + str(page)
print(url)
element_tree = html.parse(url)
rows = element_tree.xpath('//td/*/a[contains(@href, "movies/?id")]/@href')
rows_adjusted = ['http://www.boxofficemojo.com' + row + '&adjust_yr=2018' for row in rows]
# then loop over the rows_adjusted and grab the necessary info from the page如果您满意地使用熊猫数据库,我还想指出pd.read_html()函数,在我看来,它是注定要完成这项任务的。它将允许您在几乎一行中刮取一整页的字母。此外,您还可以在列之后执行任何必要的替换/注释。
一种可能的方法就是这个。
import pandas as pd
<your setup>
....
for site in major_sites:
page = 1
while True:
# fetch table
url = "http://www.boxofficemojo.com/movies/alphabetical.htm?letter=" + site + "&p=.htm&page=" + str(page)
print(url)
req = requests.get(url=url)
# pandas uses beautifulsoup to parse the html content
content = pd.read_html(req.content)
# chose the correct table from the result
tabular_data = content[3]
# drop the row with the title
tabular_data = tabular_data.drop(0)
# housekeeping renamer
tabular_data.columns = ['title', 'studio', 'total_gross', 'total_theaters',
'opening_gross', 'opening_theaters', 'opening_date']
# now you can use the pandas library to perform all necessary replacement and string operationshttps://stackoverflow.com/questions/50692065
复制相似问题