python请求发布帖子并从下拉菜单填写表单

时间:2017-10-23 08:53:00

标签: python forms post web-scraping python-requests

我正在尝试废弃此页面:

http://www.barb.co.uk/viewing-data/weekly-top-30/

我试图用这些数据填写表格:

station=BBC2 (SD+HD)
year=2016
month=January
week=11 Jan - 17 Jan

所以这就是我的尝试:

import requests
import json
url='http://www.barb.co.uk/viewing-data/weekly-top-30/'
payload= {
    'station[]':['2'],
    'period_year[]':  ['2016'],        
    'period_month[]': ['1'],
    'period_week[]': ['201601060117']                    
}
session=requests.session()
r=requests.post(url,data=payload)
with open ('html_res.html','w') as f:
    f.write(str(r.content))

html_res.html我无法获得所需的数据。 我不知道我做错了什么。 谢谢。

2 个答案:

答案 0 :(得分:1)

使用此代码。

import requests
import json

headers = {
    'Origin': 'http://www.barb.co.uk',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.8,he;q=0.6',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Accept': '*/*',
    'Referer': 'http://www.barb.co.uk/viewing-data/weekly-top-30/',
    'Connection': 'keep-alive',
}

data = [
  ('method', 'POST'),
  ('station[]', '839'),
  ('period[]', '201710060108'),
]

r = requests.post('http://barb-api.mediatel.co.uk//whats-new/weekly-top-30', headers=headers, data=data)
print(json.dumps(r.json(),indent=2))

您可以使用this网站将curl转换为python代码。

答案 1 :(得分:1)

您可以通过多种方式实现相同目标。这是一个简洁的:

import requests

payload={
'method':'POST','station[]':'2','period[]':'201601060117'
}

page = requests.post("http://barb-api.mediatel.co.uk//whats-new/weekly-top-30", params=payload)
for item in page.json():
    data = item['data']['201601060117']
    for name in data:
        print(name['programme_name'],name['data_value'],name['28_days_total'])

部分结果:

UNIVERSITY CHALLENGE (MON 2001) 3.13 3.14
TRUST ME  I'M A DOCTOR (WED 2000) 3.01 3.16
ONLY CONNECT (MON 2031) 2.7 2.75
VICTORIAN BAKERS (TUE 2001) 2.69 2.73
SNOOKER (SUN 1901) 2.11 2.12