【问题标题】:Requests post on form not returning the generated page请求在表单上发布不返回生成的页面
【发布时间】:2014-07-28 01:33:54
【问题描述】:

我想从这个网站用 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()

这只会返回原始页面,而不是我要查找的生成页面。

它没有返回生成的页面的原因可能是什么?

谢谢!

【问题讨论】:

    标签: python web-scraping beautifulsoup python-requests


    【解决方案1】:

    您需要将POST 请求的网址更改为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']
    

    【讨论】:

      猜你喜欢
      • 2021-04-14
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2021-10-19
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多