首页 > 解决方案 > 在某些使用 Requests & BeautifulSoup 或 Selenium 的网站上不完整的 HTML 响应

问题描述

我想在 Python 中使用 Requests 和 BeautifulSoup 从一些 url 中抓取信息。但有些网站只返回部分 HTML 响应,缺少页面内容

这是代码,不起作用:

import requests
from bs4 import BeautifulSoup
url = "http://www.exampleurl.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

这是不完整的回复: 图片

我尝试将 Selenium 与 Chrome Webdriver 一起使用,但最终遇到了同样的问题。

from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')
browser = webdriver.Chrome(options=options)
browser.get(url)
html = browser.page_source

有任何想法吗?

标签: pythonseleniumbeautifulsouppython-requests

解决方案


发生什么了

  1. 您没有得到预期的 html,因为它位于 iframe 中
  2. 尝试获取 iframe 的 srcsoup.find('iframe')['src']并再次请求它。

例子

import requests
from bs4 import BeautifulSoup
url = "http://www.ingenieur-jobs.de/jobangebote/3075/"
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

iframe = requests.get(soup.find('iframe')['src'])

soup = BeautifulSoup(iframe.content, 'html.parser')
soup

推荐阅读