gpt4 book ai didi

Python 在字符串中使用通配符

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:26 27 4
gpt4 key购买 nike

我正在尝试从 boxofficemoviemojo.com 抓取数据,并且我已正确设置所有内容。但是我收到一个我无法弄清楚的逻辑错误。本质上,我想获取前 100 部电影并将数据写入 csv 文件。

我目前正在使用该站点的 html 进行测试(其他年份相同):http://boxofficemojo.com/yearly/chart/?yr=2014&p=.htm

有很多代码,但这是我正在努力处理的主要部分。代码块如下所示:

def grab_yearly_data(self,page,year):
# page is the url that was downloaded, year in this case is 2014.

rank_pattern=r'<td align="center"><font size="2">([0-9,]*?)</font>'
mov_title_pattern=r'(.htm">[A-Z])*?</a></font></b></td>'
#mov_title_pattern=r'.htm">*?</a></font></b></td>' # Testing

self.rank= [g for g in re.findall(rank_pattern,page)]
self.mov_title=[g for g in re.findall(mov_title_pattern,page)]

self.rank 完美运行。但是 self.mov_title 没有正确存储数据。我想收到一个包含 102 个元素和电影片名的列表。但是我收到 102 个空字符串:''。一旦我弄清楚我做错了什么,程序的其余部分将非常简单,我只是无法在线找到我的问题的答案。我已经多次尝试更改 mov_title_pattern,但要么什么也没收到,要么收到 102 个空字符串。请帮助我真的很想推进我的项目。

最佳答案

只是don't attempt to parse HTML with regex - 它会节省您的时间,最重要的是 - 头发,会让您的生活更轻松。

这是一个使用 BeautifulSoup HTML parser 的解决方案:

from bs4 import BeautifulSoup
import requests

url = 'http://boxofficemojo.com/yearly/chart/?yr=2014&p=.htm'
response = requests.get(url)

soup = BeautifulSoup(response.content)

for row in soup.select('div#body td[colspan="3"] > table[border="0"] tr')[1:-3]:
cells = row.find_all('td')
if len(cells) < 2:
continue

rank = cells[0].text
title = cells[1].text
print rank, title

打印:

1 Guardians of the Galaxy
2 The Hunger Games: Mockingjay - Part 1
3 Captain America: The Winter Soldier
4 The LEGO Movie
...
98 Transcendence
99 The Theory of Everything
100 As Above/So Below

select() 调用中的表达式是 CSS Selector - 一种方便而强大的元素定位方式。但是,由于这个特定页面上的元素不能方便地用 id 映射或用 class 标记,我们必须依赖像 colspan 这样的属性> 或 边框[1:-3] slice 在这里用于消除标题和总行。


对于 this page , 要到达表格,您可以依赖图表元素并获取它的下一个 table 兄弟:

for row in soup.find('div', id='chart_container').find_next_sibling('table').find_all('tr')[1:-3]:
...

关于Python 在字符串中使用通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27739407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com