首先,需要确保 Beautiful Soup 抓取的是正确的网页地址,并且在代码中加入错误处理机制,以避免获取网页出错而导致程序异常退出。示例如下:
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
try:
r = requests.get(url)
r.raise_for_status()
soup = BeautifulSoup(r.content, 'html.parser')
except Exception as e:
print(e)
如果程序没有抛出异常,但是没有返回所需的数据,可以尝试查看网页源代码,并确认需要提取的信息是否包含在 html
标签中。如果是,可以使用 BeautifulSoup 的 prettify()
方法查看网页源代码,并查找需要提取的数据。
例如,假设需要获取网页上的所有超链接,可以通过以下代码实现:
links = soup.find_all('a')
for link in links:
print(link.get('href'))
如果仍然无法获取所需的数据,可能是网站使用了 AJAX 技术等异步加载数据的方式。这时可以尝试使用 Selenium 或其他模拟浏览器行为的工具来模拟浏览器操作,并获取数据。示例如下:
from selenium import webdriver
url = 'https://example.com'
driver = webdriver.Chrome()
try:
driver.get(url)
links = driver.find_elements_by_tag_name('a')
for link in links:
print(link.get_attribute('href'))
except Exception as e:
print(e)
finally:
driver.quit()
通过以上方法,基本可以解决 BeautifulSoup 抓取网页没有返回所需的数据的问题。