首页 > 解决方案 > 使用 Python 3 进行抓取

问题描述

Python3:我不熟悉抓取和训练我正在尝试从此页面获取所有功能:

https://www.w3schools.com/python/python_ref_functions.asp

from bs4 import BeautifulSoup
import requests

url = "https://www.w3schools.com/python/python_ref_functions.asp"
response = requests.get(url)
data = response.text
soup = BeautifulSoup(data, 'lxml')

print(soup.td.text)
# Output: abs()

无论我尝试什么,我只得到第一个:abs()

你能帮我把它们全部从 abs() 到 zip() 吗?

标签: python-3.xweb-scraping

解决方案


您可以使用它find_all来遍历匹配选择器的祖先:

for tag in soup.find_all('td'):
    print(tag.text)

这将包括描述列,因此您需要将其更改为忽略单元格。

soup.td 只会返回第一个匹配的标签。

所以一种解决方案是:

for tag in soup.find_all('tr'):
    cell = tag.td
    if cell:
        print(cell.text)

推荐阅读