标签: python-requests

如何一次加载无限滚动中的所有条目以解析python中的HTML

我试图从这个页面中提取信息.该页面一次加载10个项目,我需要滚动以加载所有条目(总共100个).我能够解析HTML并获取前10个条目所需的信息,但我想在解析HTML之前完全加载所有条目.

我正在使用python,requests和BeautifulSoup.我用前10个条目加载时解析页面的方式如下:

from bs4 import BeautifulSoup
import requests
s = requests.Session()
r = s.get('https://medium.com/top-100/december-2013')
page = BeautifulSoup(r.text)
Run Code Online (Sandbox Code Playgroud)

但这只会加载前10个条目.所以我查看了页面,得到了用于加载后续条目的AJAX请求,我得到了一个响应,但它是一个时髦的JSON,我宁愿使用HTML解析器而不是解析JSON.这是代码:

from bs4 import BeautifulSoup
import requests
import json
s = requests.Session()
url = 'https://medium.com/top-100/december-2013/load-more'
payload = {"count":100}
r = s.post(url, data=payload)
page = json.loads(r.text[16:]) #skip some chars that throw json off
Run Code Online (Sandbox Code Playgroud)

这给了我数据,但它是一个非常冗长和复杂的JSON,我宁愿加载页面上的所有数据,只需解析HTML.此外,呈现的HTML提供了比JSON响应更多的信息(即作者的名称而不是模糊的用户ID等).这里有类似的问题,但没有相关的答案.理想情况下,我想进行POST调用,然后请求HTML并解析它,但我无法做到这一点.

html python json beautifulsoup python-requests

20
推荐指数
2
解决办法
2万
查看次数

将请求的响应保存到文件

我正在使用请求将pdf上传到API.它存储为下面的"响应".我想把它写成一个excel.

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "w")
file.write(response)
file.close()
Run Code Online (Sandbox Code Playgroud)

我收到错误:

file.write(response)
TypeError: expected a character buffer object
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-requests

20
推荐指数
3
解决办法
6万
查看次数

使用requests.get()和requests.session().get()之间的区别?

有时我看到人们使用requests.Session对象调用Web API:

client = requests.session()
resp = client.get(url='...')
Run Code Online (Sandbox Code Playgroud)

但有时它们不会:

resp = requests.get(url='...')
Run Code Online (Sandbox Code Playgroud)

有人可以解释我们何时应该使用Session以及何时不需要它们?

python python-requests

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

如何测量Python请求POST请求的服务器响应时间?

我创建了这样的requestsPOST请求,其中我指定了超时阈值:

response = requests.post(url, data=post_fields, timeout=timeout)

但是,为了确定"良好"的阈值,我想提前对服务器响应时间进行基准测试.

如何计算服务器的最小和最大响应时间?

python network-programming python-3.x python-requests server

20
推荐指数
2
解决办法
2万
查看次数

Python 中最快的并行请求

我需要在不同的服务器上不断向大约 150 个 API 发出许多请求。我跟交易工作,时间很关键,我不能浪费1毫秒。

我发现的解决方案和问题是:

  • 使用 Asyncio 的异步:我不想依赖单个线程,因为某些原因它可能会卡住。
  • 线程:在 Python 上使用线程真的可靠吗?我有 1 个线程让
    其他线程卡住的风险吗?
  • 多进程:如果一个进程控制其他进程,我会在进程间通信中浪费很多时间吗?

也许是使用所有这些的解决方案。

如果 Python 中没有真正好的解决方案,我应该用什么来代替?

# Using Asyncio
import asyncio
import requests

async def main():
    loop = asyncio.get_event_loop()
    future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
    future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
    response1 = await future1
    response2 = await future2
    print(response1.text)
    print(response2.text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())


# Using Threads
from threading import Thread

def do_api(url):
    #...
    #...

#...
#...
for i in range(50):
    t = Thread(target=do_apis, args=(url_api[i],))
    t.start()
Run Code Online (Sandbox Code Playgroud)

python concurrency request python-requests

20
推荐指数
5
解决办法
3万
查看次数

使用csv.reader的制表符分隔文件,不分隔我期望的位置

我正在尝试使用Python循环选项卡分隔的选举结果文件.以下代码不起作用,但是当我使用具有相同结果的本地文件(注释掉的行)时,它确实按预期工作.

我唯一能想到的是我需要传递网址的一些标题或内容类型,但我无法弄清楚.

为什么会这样?

import csv
import requests

r = requests.get('http://vote.wa.gov/results/current/export/MediaResults.txt') 
data = r.text
#data = open('data/MediaResults.txt', 'r')
reader = csv.reader(data, delimiter='\t')
for row in reader:
    print row
Run Code Online (Sandbox Code Playgroud)

结果是:

...
['', '']
['', '']
['2']
['3']
['1']
['1']
['8']
['', '']
['D']
['a']
['v']
['i']
['d']
[' ']
['F']
['r']
['a']
['z']
['i']
['e']
['', '']
...
Run Code Online (Sandbox Code Playgroud)

python csv python-requests

19
推荐指数
3
解决办法
4万
查看次数

如何使用请求库从http请求中获取IP地址?

我正在使用python中的请求库发出HTTP请求,但是我需要来自响应http请求的服务器的ip地址,并且我试图避免进行两次调用(并且可能有一个不同的ip地址来自响应的那个请求.

那可能吗?有没有python http库允许我这样做?

ps:我还需要发出HTTPS请求并使用经过身份验证的代理.

更新1:

例:

import requests

proxies = {
  "http": "http://user:password@10.10.1.10:3128",
  "https": "http://user:password@10.10.1.10:1080",
}

response = requests.get("http://example.org", proxies=proxies)
response.ip # This doesn't exist, this is just an what I would like to do
Run Code Online (Sandbox Code Playgroud)

那么,我想知道从响应中的方法或属性连接的IP地址请求.在其他库中,我能够通过找到sock对象并使用getpeername()方法来做到这一点.

python pycurl httplib2 httplib python-requests

19
推荐指数
1
解决办法
3万
查看次数

请求返回字节,我无法解码它们

本质上我向一个网站提出了一个请求并得到了一个字节响应:b'[{"geonameId:"703448"}..........'. 我很困惑,因为虽然它是字节类型,但它是非常人类可读的,看起来像一个json列表.我知道响应是在latin1编码的运行r.encoding中返回的ISO-859-1,我试图解码它,但它只返回一个空字符串.这是我到目前为止所拥有的:

r = response.content
string = r.decode("ISO-8859-1")
print (string)
Run Code Online (Sandbox Code Playgroud)

这是打印空行的地方.但是,当我跑

len(string)
Run Code Online (Sandbox Code Playgroud)

我得到:返回31023 如何在不返回空字符串的情况下解码这些字节?

python byte json decoding python-requests

19
推荐指数
3
解决办法
2万
查看次数

如何让python .post()请求重试?

我正在尝试在Python中实现请求重试.
它与.get()请求的魅力相似,但.post()无论状态代码如何,请求都不会重试.我想将它与.post()请求一起使用.

我的代码:

from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from requests import Session, exceptions

s = Session()
s.mount('http://', HTTPAdapter(max_retries=Retry(total=2, backoff_factor=1, status_forcelist=[ 500, 502, 503, 504, 521])))
r = s.get('http://httpstat.us/500')
r2 = s.post('http://httpstat.us/500')
Run Code Online (Sandbox Code Playgroud)

因此,.get()请求会重试,而请求.post()则不会.

怎么了?

python urllib3 python-requests

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

Simple get/post request blocked in python 3 but not in python 2

I'm working on a simple web scraper in python 3 but when I send a get or a post request, the response is 403. In python 2 works fine though. I'm using the same version of requests libraries in both versions. I have also tried with Verify=False/True but the difference in both versions remains.

requests = 2.22.0

certifi = 2019.9.11

from requests import get
url = 'https://www.gamestop.com/'
header = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.5',
    'User-Agent': 'Mozilla/5.0 …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x python-requests

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