url="https://technet.microsoft.com/enus/library/hh135098(v=exchg.150).aspx"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'lxml')
table = soup.find_all('table', attrs={"responsive": "true"})[0]
for rows in table.find_all('tr')[1:2]:
item = []
for val in rows.find_all('td'):
item.append(val.text.strip())`
我试图在同一网站上的 4 个不同表中循环它,但我不知道如何编写循环。我已经对此进行了研究,但似乎不知道该怎么做
这 4 个表位于位置 0、1、2 和 6。我尝试对数据进行切片以包含它们,但似乎没有任何效果
最佳答案
您可以找到所有符合您的过滤条件的表格,使用enumerate()
获取索引并“过滤掉”不需要索引的表:
desired_indexes = {0, 1, 2, 6}
tables = soup.find_all('table', attrs={"responsive": "true"})
for index, table in enumerate(tables):
if index not in desired_indexes:
continue
# do something with table
不过,一般来说,依赖页面上元素的出现索引听起来并不是一种在页面上定位元素的可靠技术。
关于 python : Scraping through multiple tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43853128/