【发布时间】:2019-10-09 07:10:30
【问题描述】:
我正在尝试抓取此 URL,因此我只能获取某些索引。在这种情况下,我的示例显示我可以抓取索引 6,这将为我提供任何以 /wiki/ 开头的 url。这将为我提供所有以 A 开头的 TLD。我想获取所有与我的任务相关的索引。
截至目前,我已尝试将它们列为 [6、7、8 等] 并在引号中列出。不过,我对列表的工作并不多,我需要花更多时间学习。
import requests
from bs4 import BeautifulSoup
page = requests.get('https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains')
soup = BeautifulSoup(page.text, 'lxml')
table = soup.findAll('table')[6]
for record in table.findAll('tr'):
for data in record.findAll('td'):
for link in data.select("a[href^='/wiki/.']"):
links = link.contents[0]
print(links)
但是,由于我是编程新手,我不知道如何添加除 6 之外的多个索引。这些是我收到的错误:
======= RESTART: /run/media/sean/The Continuum/Python/wikinamelist.py =======
Traceback (most recent call last):
File "/run/media/sean/The Continuum/Python/wikinamelist.py", line 7, in <module>
table_data = soup.find_all('table')["6", "7"]
TypeError: list indices must be integers or slices, not tuple
>>>
======= RESTART: /run/media/sean/The Continuum/Python/wikinamelist.py =======
Traceback (most recent call last):
File "/run/media/sean/The Continuum/Python/wikinamelist.py", line 7, in <module>
table_data = soup.find_all('table')[6, 7];
TypeError: list indices must be integers or slices, not tuple
>>>
======= RESTART: /run/media/sean/The Continuum/Python/wikinamelist.py =======
Traceback (most recent call last):
File "/run/media/sean/The Continuum/Python/wikinamelist.py", line 7, in <module>
table_data = soup.find_all('table')[6, 7, 8];
TypeError: list indices must be integers or slices, not tuple
正如您在上面看到的,我尝试了多种方法,并在错误消息中显示。
任何反馈都将不胜感激,谢谢!
【问题讨论】:
标签: python html web-scraping beautifulsoup