【问题标题】:Scrape more than one form from webpage using beautiful soup使用漂亮的汤从网页中刮取多个表格
【发布时间】:2017-10-16 15:57:07
【问题描述】:

一个网页中有两种形式。我正在尝试使用以下代码抓取网页 (http://demo.testfire.net/feedback.aspx) 的所有表单和相关属性:

import bs4 as bs 
import urllib.request

sauce = urllib.request.urlopen("http://demo.testfire.net/feedback.aspx").read()
soup = bs.BeautifulSoup(sauce,"html.parser")

form_count = 0
for form_list in soup.find_all('form'):
    form_count+=1
    action_value = soup.find('form').get('action')
    method_value = soup.find('form').get('method')
    id_value = soup.find('form').get('id')
    print(form_count, action_value, method_value, id_value)

但是,只有页面的第一种形式会被打印两次。如何同时抓取表单及其属性? 注意:form_count 变量递增到 2(因为页面中有 2 个表单)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您使用soup.find('form'),它返回它在页面上找到的第一个表单,而不是form_list,它返回当前表单,同时遍历所有表单。你的代码应该是这样的

    import bs4 as bs 
    import urllib.request
    
    sauce = urllib.request.urlopen("http://demo.testfire.net/feedback.aspx").read()
    soup = bs.BeautifulSoup(sauce,"html.parser")
    
    form_count = 0
    for form_list in soup.find_all('form'):
        form_count+=1
        action_value = form_list.get('action')
        method_value = form_list.get('method')
        id_value = form_list.get('id')
        print(form_count, action_value, method_value, id_value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多