python-3.x - 如何从不同的页面中提取表格?(Python)
问题描述
我想在 http:// 上提取第一个薮页的表格
这些表已经被下面的代码刮掉了,它们在一个列表中,从 bs4 import BeautifulSoup 导入 urllib
base_url = "http://"
url_list = ["{}?page={}".format(base_url, str(page)) for page in range(1, 21)]
mega = []
for url in url_list:
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table', {'class': 'table table-bordered table-striped table-hover'})
mega.append(table)
因为它是一个列表,不能使用 'soup find_all' 来提取我想要的项目,所以我将它们转换为 bs4.element.Tag 以进一步搜索项目
for i in mega:
trs = table.find_all('tr')[1:]
rows = list()
for tr in trs:
rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])
rows
这些行仅提取最后一页的表格。我的代码有什么问题,所以之前的 19 个表没有被提取出来?谢谢!
这两个项目的长度不相等。我在meaga中使用for i来获得i。
len(mega) = 20
len(i) = 5
解决方案
问题很简单。在这个 for 循环中:
for i in mega:
trs = table.find_all('tr')[1:]
rows = list()
for tr in trs:
rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])
rows = list()
您在 for 循环中进行初始化。所以你循环了 21 次,但你也清空了 20 次列表。
所以你需要这样:
rows = list()
for i in mega:
trs = table.find_all('tr')[1:]
for tr in trs:
rows.append([td.text.replace('\n', '').replace('\xa0', '').replace('\t', '').strip().rstrip() for td in tr.find_all('td')])
推荐阅读
- swift - 如何通过取消按钮中的选择发送打击
- charles-proxy - 如何启用本地地图以读取查尔斯中的帖子数据
- kubernetes - 如何向 Kubernetes helm 模板添加默认值
- c# - 反序列化 Json 时错误的 JSON 转义序列
- c# - C# 中的 HTML 表格格式不正确
- c# - 尝试调用 Singleton 方法时出现 System.StackOverflowException
- javascript - 从 ReactJs 的数组中定义的函数中获取参数
- java - 流过滤方法不是每次都执行
- ruby - Minitest 是否有类似于 RSpec 中的 allow_any_instance_of 的东西?
- javascript - 检查函数是否在jQuery中返回false