我想提取http://上的第一服务页面的表格
表格已被下面的代码抓取,并在列表中,从bs4导入urllib导入BeautifulSoup
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中用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')])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句