【问题标题】:BeautifulSoup does not extract all forms from web pageBeautifulSoup 不会从网页中提取所有表单
【发布时间】:2017-08-19 13:26:46
【问题描述】:

我希望使用 Python3 和 BeautifulSoup 从给定网站中提取所有表单。

这是一个这样做的例子,但无法获取所有表单:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://www.qantas.com/au/en.html'
data = urlopen(url)
parser = BeautifulSoup(data, 'html.parser')
forms = parser.find_all('form')
for form in forms:
    print(form)
    print('\n\n')

如果您运行代码并访问 URL,您会注意到 Book a trip 表单没有被解析器抓取。

上面的代码只选择了三种形式,而在 Chrome 的 Developers tools > elements 页面中显示了 13 个 <form> 元素。但是如果我查看页面源(Chrome 中的Ctrl+U),源只显示了BeautifulSoup 抓取的三个表单。

如何抓取所有表单?

【问题讨论】:

  • 不确定这里发生了什么,但是如果您转到该页面的“查看源代码”,它只会显示三个表单,这正是您所得到的。会不会是其他表单是在页面加载之后从服务器请求生成的?

标签: python html forms web-scraping beautifulsoup


【解决方案1】:

借助 phantomjs(http://phantomjs.org/download.html) 和 Selenium,您可以做到这一点

步骤:1.在终端或cmd使用命令:pip install selenium 2.下载phantomjs并解压,然后将“phantomjs.exe”放在python路径,例如windows,C:\Python27

比起使用这个代码,它会给你想要的结果:

# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup
from  selenium import webdriver


url = 'https://www.qantas.com/au/en.html'


driver = webdriver.PhantomJS()
driver.get(url)

data = driver.page_source
parser = BeautifulSoup(data, 'html.parser')


forms = parser.find_all('form')
for form in forms:
    print(form)
    print('\n\n')

driver.quit()

它将打印所有 13 个表格。

注意:由于字数限制,无法在答案中输出。

【讨论】:

    【解决方案2】:

    该网页似乎使用 JavaScript 来加载网页内容。尝试使用javascript disabled 在浏览器中查看该页面。

    检查您的表单是否存在。如果不是,请检查是否是控制台中的任何 XHR 请求获取表单。如果没有,你应该考虑去selenium with phantomjs无头浏览器或者放弃对本站的抓取!!

    无头浏览器将允许您获取动态创建的网页的内容并将该内容提供给 BeautifulSoup。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多