Pandas 从 URL 读取_csv 并包含请求标头 [英] Pandas read_csv from URL and include request header

查看:45
本文介绍了Pandas 从 URL 读取_csv 并包含请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 Pandas 0.19.2 开始,函数 read_csv() 可以传递一个 URL.例如,请参阅此答案:

As of Pandas 0.19.2, the function read_csv() can be passed a URL. See, for example, from this answer:

import pandas as pd

url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
c=pd.read_csv(url)

<小时>

我想使用的 URL 是:https://moz.com/top500/domains/csv

使用上面的代码,这个网址返回一个错误:

With the above code, this URL returns an error:

urllib2.HTTPError: HTTP Error 403: Forbidden

基于这篇文章,我可以通过传递请求头来获得有效响应:

based on this post, I can get a valid response by passing a request header:

import urllib2,cookielib

site= "https://moz.com/top500/domains/csv"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

req = urllib2.Request(site, headers=hdr)

try:
    page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print (e.fp.read())

content = page.read()
print (content)

有没有什么办法可以使用 Pandas read_csv() 的网址功能,同时也传递一个请求头来让请求通过?

Is there any way to use the web URL functionality of Pandas read_csv(), but also pass a request header to make the request go through?

推荐答案

我建议您使用 requestsio 库用于您的任务.以下代码应该可以完成这项工作:

I would recommend you using the requests and the io library for your task. The following code should do the job:

import pandas as pd
import requests
from io import StringIO

url = "https://moz.com:443/top500/domains/csv"
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0"}
req = requests.get(url, headers=headers)
data = StringIO(req.text)

df = pd.read_csv(data)
print(df)

(如果你想添加自定义标题,只需修改 headers 变量)

希望能帮到你

这篇关于Pandas 从 URL 读取_csv 并包含请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆