python - 用 python 抓取 .aspx 页面

标签 python asp.net beautifulsoup

我是网络抓取游戏的新手。我正在尝试删除以下网站: http://www.foodemissions.com/foodemissions/Calculator.aspx

使用在 Internet 上找到的资源,我整理了以下 HTTP POST 请求:

import urllib
from bs4 import BeautifulSoup

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept-Encoding': 'gzip,deflate,sdch',
    'Accept-Language': 'en-US,en;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}

class MyOpener(urllib.FancyURLopener):
    version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'

myopener = MyOpener()
url = 'http://www.foodemissions.com/foodemissions/Calculator.aspx'
# first HTTP request without form data
f = myopener.open(url)
soup_dummy = BeautifulSoup(f,"html5lib")
# parse and retrieve two vital form values
viewstate = soup_dummy.select("#__VIEWSTATE")[0]['value']
viewstategen = soup_dummy.select("#__VIEWSTATEGENERATOR")[0]['value']

soup_dummy.find(id="ctl00_MainContent_category")

#search for the string 'input' to find the form data
formData = (
    ('__VIEWSTATE', viewstate),
    ('__VIEWSTATEGENERATOR', viewstategen),
    ('ctl00$MainContent$transport', '200'),
    ('ctl00$MainContent$quantity','1'),
    ('ctl00$MainContent$wastepct','100')
)

encodedFields = urllib.urlencode(formData)
# second HTTP request with form data
f = myopener.open(url, encodedFields)
soup = BeautifulSoup(f,"html5lib")
trans_emissions = soup.find("span", id="ctl00_MainContent_transEmissions")
print(trans_emissions.text)

即使我更改了 ctl00$MainContent$transport 元素,我最终打印命令的输出似乎也没有改变。关于为什么会这样的任何指示?

谢谢!

最佳答案

您需要通过将按钮名称添加到 __EVENTTARGET 隐藏输入,使 ASP.NET 应用“认为”您单击了计算按钮。

formData = (
    ('__VIEWSTATE', viewstate),
    ('__VIEWSTATEGENERATOR', viewstategen),
    ('ctl00$MainContent$transport', '100'),
    ('ctl00$MainContent$quantity','150'),
    ('ctl00$MainContent$wastepct','200'),
    ('__EVENTTARGET', 'ctl00$MainContent$calculate')
)

关于python - 用 python 抓取 .aspx 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46395314/

相关文章:

python - 使用 Python BeautifulSoup 查找页数

python - 如何使用 Chrome 的 webdriver 单击由节点/角度脚本按钮生成的 'Next page'?

c# - 为什么通过TCP发送后字节序颠倒了

python - 捕获最多三位数的所有数字

python - 调用 pyplot.show() 后保存图形会导致一个空文件

c# - ASP.NET MVC 3 : Is there a way to get a controller's string Name from its Type?

asp.net - 将动态数据添加到现有站点时出错 - 'Skip' 仅支持 LINQ to Entities 中的排序输入。 'OrderBy' 必须在 'Skip' 之前调用

ASP.NET 页面说我需要引用一个不存在的程序集!

python - 使用漂亮的汤来获取html属性值

python - 为什么即使具有相同的值,Python 也会为列表、元组、字典分配新的 id?