标签: python-requests

带有请求的 HTTPS 代理:[Errno 8] _ssl.c:504:发生 EOF 违反协议

我在 Windows 7 x64 上使用 Requests 1.2.3,并尝试通过将参数传递proxies给请求,使用 HTTPS 代理通过 HTTPS 连接到(任何)站点。

urllib2我在使用's时没有遇到此错误ProxyHandler,所以我认为它不在我的代理这边。

>>> opener = urllib2.build_opener(urllib2.ProxyHandler({'https': 'IP:PORT'}))
>>> resp = opener.open('https://www.google.com')
>>> resp.url
'https://www.google.co.uk/'
>>> resp = requests.get('https://www.google.com', proxies={'https': 'IP:PORT'})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\requests\api.py", line 55, in get
    return request('get', url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 335, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 438, …
Run Code Online (Sandbox Code Playgroud)

python ssl https proxy python-requests

1
推荐指数
1
解决办法
3521
查看次数

Python:使用 reuests 库进行多部分/表单数据

我对此相当菜鸟,并且一直在尝试将requests模块用于post多部分/表单数据。为了澄清这一点,我尝试使用的确切测试用例与https://github.com/kennethreitz/requests/issues/1081中的测试用例相同 。即我正在尝试执行post没有文件的操作:

--3eeaadbfda0441b8be821bbed2962e4d
Content-Disposition: form-data; name="key1"

value1
--3eeaadbfda0441b8be821bbed2962e4d
Run Code Online (Sandbox Code Playgroud)

根据线程上的讨论,我尝试了多部分表单数据方案来执行以下操作:

import requests
from requests_data_schemes import multipart_formdata as mfd
post_data = [('mouseAction', 'toggle'), ('zone' ,'10')]
post_data = mfd(post_data)
headers = {'Content-Type': 'multipart/form-data'}

req = requests.post(<url>, data=post_data, headers=headers)
Run Code Online (Sandbox Code Playgroud)

但是,测试服务器向我抛出一个错误,指出它无法检测多部分表单数据的边界。

我也尝试在标题中提供边界,但显然它不起作用。

boundary = post_data[2: post_data.find('\r\n')]
headers = {'Content-Type': 'multipart/form-data; boundary={}'.format(boundary)}
Run Code Online (Sandbox Code Playgroud)

我错过了一些简单的事情吗?

PS:通过一些冲浪,我发现了一些使用 base 的解决方案urllib2,但这将是我最后的手段,因为requests它让我可以轻松地做很多事情。

python multipartform-data python-2.7 python-requests

1
推荐指数
1
解决办法
2786
查看次数

python请求检查文件是否正确下载

我正在使用requestslib 从网站下载一些图像。
我的代码会在下载后检查文件大小。
示例代码:

def download(url, store_dir):
    r = requests.get(url, headers=headers, proxies=proxies)

    filename = r.headers.get('content-disposition').split('=')[1]

    real_length = int(r.headers.get('content-length'))

    wholepath = os.path.join(store_dir, filename)

    with open(wholepath, 'wb') as f:
        f.write(r.content)
        f.close()

    if os.path.getsize(wholepath) != real_length:
        print('size error')
        print('status_code: %s' %r.status_code)
        print('headers: %s' %r.headers)
        print('url"%s' % url)
        print('orgin:', r.headers['content-length'], 'now',os.path.getsize(wholepath))
        self.download(url, store_dir)
Run Code Online (Sandbox Code Playgroud)

但我通常会发现即使os.path.getsize(wholepath) == real_length.
我怎么解决这个问题?

python download python-2.7 python-requests

1
推荐指数
1
解决办法
3046
查看次数

BeautifulSoup:如何获取 div 选项卡的子级

这是我的代码。

 import requests
 from bs4 import BeautifulSoup
 res = requests.get('http://www.snapdeal.com/products/computers-laptops?sort=plrty&')
 soup = BeautifulSoup(res.text)
 price = soup.find_all('div', class_="product-price").children
Run Code Online (Sandbox Code Playgroud)

我想从这个网站上抓取数据,但该 div 没有类,这就是为什么我不知道该怎么做,然后我发现你可以找到 div 标签的子级,但它也不起作用,我正在尝试获取所有标签。

python beautifulsoup python-requests

1
推荐指数
1
解决办法
2470
查看次数

如何使用 python 请求发布 JSON/xml 文件的多部分列表

在 python2.7 中,我用来requests与 REST 端点进行通信。我可以向其中上传单个 JSON 和 xml 对象。为了加快速度,我想使用 multipart 上传多个 json 对象。

我有一个curl 命令,它展示了如何完成它并且它是有效的。我需要在 python requests POST 命令中翻译它。

工作卷曲杆:

curl --anyauth --user admin:admin -X POST --data-binary \@sample-body \
     -i -H "Content-type: multipart/mixed; boundary=BOUNDARY" \
     "http://localhost:8058/v1/resources/sight-ingest?rs:transform=aireco-transform&rs:title=file1.xml&rs:title=file2.xml&rs:title=file3.xml"
Run Code Online (Sandbox Code Playgroud)

需要注意的是:我需要发送自定义参数列表,包括“标题”参数列表,不能通过传递字典来做到这一点吗?但我们可以解决这个问题。

我的蟒蛇足迹:

import requests
files = {'file1': ('foo.txt', 'foo\ncontents\n','text/plain'), 
          'file2': ('bar.txt', 'bar contents', 'text/plain'),
          'file3': ('baz.txt', 'baz contents', 'text/plain')}

headers = {'Content-Type': 'multipart/mixed','Content-Disposition': 'attachment','boundary': 'GRENS'}
params={'title':'file1','title':'file2','title':'file2'}
r = requests.Request('POST', 'http://example.com', files=files , headers=headers, params=params)
print r.prepare().url
print r.prepare().headers
print r.prepare().body
Run Code Online (Sandbox Code Playgroud)

给我:

http://example.com/?title=file2 …
Run Code Online (Sandbox Code Playgroud)

python python-requests

1
推荐指数
1
解决办法
7575
查看次数

Python requests 模块多线程

有没有可能使用多处理接口来加速我的代码?问题是这个接口使用了map函数,它只适用于1个函数。但我的代码有3个功能。我尝试将我的功能合并为一个,但没有成功。我的脚本从文件中读取站点的 URL 并对其执行 3 个功能。For 循环使它非常慢,因为我有很多 URL

import requests

def Login(url): #Log in     
    payload = {
        'UserName_Text'     : 'user',
        'UserPW_Password'   : 'pass',
        'submit_ButtonOK'   : 'return buttonClick;'  
      }

    try:
        p = session.post(url+'/login.jsp', data = payload, timeout=10)
    except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
        print "site is DOWN! :", url[8:]
        session.cookies.clear()
        session.close() 
    else:
        print 'OK: ', p.url

def Timer(url): #Measure request time
    try:
        timer = requests.get(url+'/login.jsp').elapsed.total_seconds()
    except (requests.exceptions.ConnectionError):
        print 'Request time: None'
        print '-----------------------------------------------------------------'
    else: 
        print 'Request time:', round(timer, 2), 'sec'

def Logout(url): # Log out …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-2.7 python-requests python-multiprocessing

1
推荐指数
1
解决办法
7558
查看次数

Python 使用 python 下载 twitter 视频(不使用 twitter api)

我想在不使用 twitter 的官方 API 的情况下下载 twitter 视频。因此,当我在 chrome 中打开 icognito 和 chrome 开发工具并请求任何像“ https://twitter.com/KTHopkins/status/1248140219490209792 ”这样的视频时,我看到 twitter 请求两个重要的标题来为视频提供服务 1.'授权' 2。 'x-客人-令牌'

我似乎无法获得这些令牌是从哪里生成的?下面是我发送的 python 请求。

import requests

headers = {

    'authority': 'api.twitter.com',

    'dnt': '1',

    'x-twitter-client-language': 'en',

    # 'x-csrf-token': '6089ceeab3324243e7b952679b2b7851',

    'authorization': 'Bearer AAAAAAAAAAAAAAAAAAAAANk3DgEAAAAAB0pZx4xjgXBOoalj%2FRbagurxD2M%3DG8634UVlBud8LrLG4nGo7FpN2RCO2xul5BuPKHuejUAV14O0KG',

    'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',

    'sec-fetch-dest': 'empty',

    'x-guest-token': '1248286947669237760',

    'x-twitter-active-user': 'yes',

    'accept': '*/*',

    'origin': 'https://twitter.com',

    'sec-fetch-site': 'same-site',

    'sec-fetch-mode': 'cors',

    'accept-language': 'en-US,en;q=0.9,hi;q=0.8',

    # 'cookie': 'personalization_id="v1_tWyK8Fn5ofSPjSAEKsnyrw=="; guest_id=v1%3A158644503604220835; ct0=6089ceeab3324243e7b952679b2b7851; _twitter_sess=BAh7CSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCDI2fl9xAToMY3NyZl9p%250AZCIlNmM2YjZiYTU4MzdhY2FkNDQwZjcwMGU1NDliNzEzN2Y6B2lkIiViOWUx%250AYzM5MDk3ZTQ0YzMyZDRkMGU3YTdkM2FlMGY2YQ%253D%253D--223c07ac4708a9bec30dec1e0e9c3d52544b310c; _ga=GA1.2.162154316.1586445033; _gid=GA1.2.1445748635.1586445033; gt=1248286947669237760',

}

response …
Run Code Online (Sandbox Code Playgroud)

python twitter python-requests

1
推荐指数
2
解决办法
3017
查看次数

无法使用请求从网页中获取某些字段

我正在尝试使用模块从这个网页中获取不同容器的标题和链接requests,但我找不到任何方法来做到这一点。我试图找到任何通常出现在开发工具中的隐藏 API,但我失败了。我注意到在不同的时候,动态生成的内容大部分时间都在某些脚本标签中可用。但是,在这种情况下,我也找不到其中的内容。作为最后的手段,我使用 Selenium 来获取它们。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

link = 'https://www.firmy.cz/kraj-praha?q=prodej+kol'

def get_content(url):
    driver.get(url)
    for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'.companyDetail'))):
        item_link = item.find_element_by_css_selector("h3 > a.companyTitle").get_attribute("href")
        item_title = item.find_element_by_css_selector("span.title").text
        yield item_link,item_title

if __name__ == '__main__':
    with webdriver.Chrome() as driver:
        wait = WebDriverWait(driver,10)
        for item in get_content(link):
            print(item)
Run Code Online (Sandbox Code Playgroud)

脚本产生的结果如下:

('https://www.firmy.cz/detail/12824790-bike-gallery-s-r-o-praha-vokovice.html', 'Bike Gallery s.r.o.')
('https://www.firmy.cz/detail/13162651-bikeprodejna-cz-praha-dolni-chabry.html', 'BIKEPRODEJNA.CZ')
('https://www.firmy.cz/detail/406369-bikestore-cz-praha-podoli.html', 'Bikestore.cz')
('https://www.firmy.cz/detail/12764331-shopbike-cz-praha-ujezd-nad-lesy.html', 'Shopbike.cz')
Run Code Online (Sandbox Code Playgroud)

如何使用请求模块获取相同的结果?

python web-scraping python-3.x python-requests

1
推荐指数
1
解决办法
105
查看次数

无法使用请求从网页中收集某些值

我正在尝试从网页中的表格中获取一些动态值。此图像表示我希望从该页面获取的值。应该有任何方法可以使用请求来获取它们。为了让您知道,我在开发工具中查找了任何隐藏的 api,还通过页面源代码中的脚本标签查找了值,但我找不到。

这是网站网址

这是我所追求的预期输出。

这是我到目前为止写的:

import requests
from bs4 import BeautifulSoup

url = "https://www.dailyfx.com/sentiment"

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}

r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.text,"lxml")
for items in soup.select(".dfx-technicalSentimentCard__barContainer"):
    data = [item.get("data-value") for item in items.select("[data-type='long-value-info'],[data-type='short-value-info']")]
    print(data)
Run Code Online (Sandbox Code Playgroud)

上面的脚本产生如下的空输出:

['--', '--']
['--', '--']
['--', '--']
['--', '--']
['--', '--']
['--', '--']
['--', '--']
Run Code Online (Sandbox Code Playgroud)

如何使用请求从该表中获取值?

python beautifulsoup web-scraping python-requests

1
推荐指数
1
解决办法
260
查看次数

在 Python 中以请求 get() 方法为前缀的字典

我目前正在查看财务 API 的一些代码,并且有一个示例函数似乎可以处理指定类型的请求(我对请求很陌生,所以仍在学习这个)。
我不明白函数 return 中的语法。我从来没有见过这样的方法前面的字典,这里发生了什么?感谢您的建议。

import requests 

def dispatch_request(http_method):
    session = requests.Session()
    session.headers.update({
        'Content-Type': 'application/json;charset=utf-8',
        'X-MBX-APIKEY': KEY
    })
    return {
        'GET': session.get,
        'DELETE': session.delete,
        'PUT': session.put,
        'POST': session.post,
    }.get(http_method, 'GET')
Run Code Online (Sandbox Code Playgroud)

如果有人对完整示例感兴趣,可以在此处查看:https : //github.com/binance-exchange/binance-signature-examples/blob/master/python/spot.py

python session dictionary get python-requests

1
推荐指数
1
解决办法
49
查看次数