Python POST请求

时间:2017-04-18 16:37:13

标签: python python-requests

我正在使用python请求搜索以下网站:https://www.investing.com/以获取“耐用品订单美国”这一术语

我检查了检查面板的“网络”标签,看起来只是使用以下表格完成:'quotes_search_text':'耐用品订单美国'

所以我尝试使用python:

URL = 'https://www.investing.com/'
data = {'quotes_search_text':'Durable Goods Orders US'}
resp = requests.post(URL, data=data, headers={ 'User-Agent': 'Mozilla/5.0', 'X-Requested-With': 'XMLHttpRequest'})

然而,这并不会返回我手动执行时可以看到的结果。 所有搜索结果都应该有“gs-title”作为类属性(根据页面检查),但是当我这样做时:

soup = BeautifulSoup(resp.text, 'html.parser')
soup.select(".gs-title")

我看不到结果...... 我没有考虑到POST请求的某些方面吗? (我是一个完整的菜鸟)

1 个答案:

答案 0 :(得分:1)

在聊天中详细讨论后,有很多变化。为了检索您要查找的信息,您需要运行正在运行的JS。您可以将query变量更改为您想要的任何内容。

import requests
import json
from urllib.parse import quote_plus

URL = 'https://www.googleapis.com/customsearch/v1element'

query = 'Durable Goods Orders US'
query_formatted = quote_plus(query)

data = {
    'key':'AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY',
    'num':10,
    'hl':'en',
    'prettyPrint':'true',
    'source':'gcsc',
    'gss':'.com',
    'cx':'015447872197439536574:fy9sb1kxnp8',
    'q':query_formatted,
    'googlehost':'www.google.com'
}
headers = {
    'User-Agent':'Mozilla/5.0',
    'Referer':'https://www.investing.com/search?q=' + query_formatted,
}
resp = requests.get(URL, params=data, headers=headers)

j = json.loads(resp.text)
# print(resp.text)
for r in j['results']:
    print(r['title'], r['url'])