ove*_*iew 1 python search login beautifulsoup urllib3
import urllib3
import io
from bs4 import BeautifulSoup
import re
import cookielib
http = urllib3.PoolManager()
url = 'http://www.example.com'
headers = urllib3.util.make_headers(keep_alive=True,user_agent='Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6')
r = http.urlopen('GET', url, preload_content=False)
# Params die dann am Post request übergeben werden
params = {
'login': '/shop//index.php',
'user': 'username',
'pw': 'password'
}
suche = {
'id' : 'searchfield',
'name' : 'suche',
}
# Post Anfrage inkl params (login) Antwort in response.data
response = http.request('POST', url, params, headers)
suche = http.request('POST', site-to-search? , suche, headers)
html_suche = suche.data
print html_suche
Run Code Online (Sandbox Code Playgroud)
我尝试使用此代码登录到一个站点并在此之后进行搜索。使用此代码,我得到一个我未登录的答案。
我怎样才能将我第一次登录和之后搜索结合起来。谢谢。
Web 服务器通过设置客户端必须返回的 cookie 来跟踪类似浏览器的客户端状态。默认情况下,urllib3
不会伪装成浏览器,因此我们需要做一些额外的工作来将 cookie 中继回服务器。以下是如何使用httpbin.org执行此操作的示例:
import urllib3
http = urllib3.PoolManager()
# httpbin does a redirect right after setting a cookie, so we disable redirects
# for this request
r = http.request('GET', 'http://httpbin.org/cookies/set?foo=bar', redirect=False)
# Grab the set-cookie header and build our headers for our next request.
# Note: This is a simplified version of what a browser would do.
headers = {'cookie': r.getheader('set-cookie')}
print headers
# -> {'cookie': 'foo=bar; Path=/'}
r = http.request('GET', 'http://httpbin.org/cookies', headers=headers)
print r.body
# -> {
# "cookies": {
# "foo": "bar"
# }
# }
Run Code Online (Sandbox Code Playgroud)
(注意:这个秘籍很有用,urllib3
拥有它的文档会从中受益。我很感激一个拉取请求,它为此效果添加了一些东西。)
Martijn 提到的其他选项是使用更高级的库,伪装成更像浏览器。robobrowser
看起来是此类工作的绝佳选择,但也requests
提供了为您管理 cookie 并在其下使用的规定urllib3
。:)