python - 请求在表单上发布不返回生成的页面

标签 python web-scraping beautifulsoup python-requests

我想用 python 从这个网站抓取:http://www.ssa.gov/oact/babynames/#ht=1

在底部的名称表下方,有三个选项卡。我希望将帖子发布到“按出生年份列出的流行名字”选项卡下的表单。

这是我的代码:

from bs4 import BeautifulSoup
import requests

url = "http://www.ssa.gov/oact/babynames/"

payload = {
    'year': 2010,
    'top': 50
}

r = requests.post(url, data=payload)
# returns status 200

soup = BeautifulSoup(r.text)

print soup.prettify()

这仅返回原始页面,而不是我正在查找的生成页面。

不返回生成页面的原因可能是什么?

谢谢!

最佳答案

您需要将 POST 请求的 URL 更改为 http://www.ssa.gov/cgi-bin/popularnames.cgi .

演示:

>>> from bs4 import BeautifulSoup
>>> import requests
>>> url = "http://www.ssa.gov/cgi-bin/popularnames.cgi"
>>> payload = {
...     'year': 2010,
...     'top': 50
... }
>>> r = requests.post(url, data=payload)
>>> soup = BeautifulSoup(r.text)
>>> table = soup.find('table', summary='Popularity for top 50')
>>> for row in table.find_all('tr')[1:4]:
...     print [td.text for td in row.find_all('td')]
... 
[u'1', u'Jacob', u'Isabella']
[u'2', u'Ethan', u'Sophia']
[u'3', u'Michael', u'Emma']

关于python - 请求在表单上发布不返回生成的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24087613/

相关文章:

python - 如何递归遍历所有子目录并读取文件?

Python BeautifulSoup 获取图像、文本和 URL

python - 安装脚本退出并出现错误 : command 'x86_64-linux-gnu-gcc' failed with exit status 1

python - 从 numpy 和 scipy.sparse 准备 tensorflow 的数据输入

javascript - CasperJS,使用javascript禁用来抓取目标页面中的内容

python - 使用 Beautifulsoup 解析后写入 csv 会导致分离值或空输出文件

python - 如何构建 html5lib 解析器来处理 XML 和 HTML 标签的混合?

python - BeautifulSoup 获取具有特定类的 div 中所有 img 的多个元素

python - 当包含 NaN 时使用 "new information"更新 Pandas 数据帧

python - 从下拉选项值 Python BeautifulSoup 中抓取