如何使用Python读取URL的内容?


93

当我将其粘贴到浏览器中时,以下方法起作用:

http://www.somesite.com/details.pl?urn=2344

但是,当我尝试使用Python读取URL时,没有任何反应:

 link = 'http://www.somesite.com/details.pl?urn=2344'
 f = urllib.urlopen(link)           
 myfile = f.readline()  
 print myfile

我需要对URL进行编码,还是没有看到什么?

Answers:


156

要回答您的问题:

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.read()
print(myfile)

您需要read(),而不是readline()

编辑(2018-06-25):自Python 3起,旧版urllib.urlopen()被替换为urllib.request.urlopen()(有关详细信息,请参阅https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen中的注释) 。

如果您使用的是Python 3,请在此问题中查看Martin Thoma或innm的答案:https ://stackoverflow.com/a/28040508/158111 (Python 2/3兼容) https://stackoverflow.com/a/45886824 / 158111(Python 3)

或者,只需在此处获取此库:http : //docs.python-requests.org/en/latest/并认真使用它即可:)

import requests

link = "http://www.somesite.com/details.pl?urn=2344"
f = requests.get(link)
print(f.text)

@KiranSubbaraman,这是一个非常不错的项目,从API到代码结构
woozyking 2015年

我还建议并鼓励程序员使用新的品牌requests模块,它的使用产生了更多的Pythonic代码。
汉斯·齐默尔曼

1
我在python 3.5.2上遇到以下错误:Traceback (most recent call last): File "/home/lars/parser.py", line 9, in <module> f = urllib.urlopen(link) AttributeError: module 'urllib' has no attribute 'urlopen'似乎在python 3.5中没有urlopen函数。它被重命名了吗?编辑:下面的答案摘录解决了:from urllib.request import urlopen
LMD

@ user7185318是,在Python 3中,该urlib软件包进行了一些重构和API更改。我将更新答案以强调Python2。–
woozyking

如果提供的链接要求输入用户名和密码怎么办?那么如何更改代码?
埃森博士,

27

对于python3用户,为节省时间,请使用以下代码,

from urllib.request import urlopen

link = "https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"

f = urlopen(link)
myfile = f.read()
print(myfile)

我知道有不同的错误线程:Name Error: urlopen is not defined,但认为这样可以节省时间。


这不是使用python3从url读取数据的最佳方法,因为它错过了“ with”语句的好处。见我的答案:stackoverflow.com/a/56295038/908316
Jared

不,这在while循环上不起作用。仅一个电话。如果您问我,这很烂
lone_coder

10

与Python 2.X和Python 3.X配合使用的解决方案利用了Python 2和3兼容性库six

from six.moves.urllib.request import urlopen
link = "http://www.somesite.com/details.pl?urn=2344"
response = urlopen(link)
content = response.read()
print(content)

8

这些答案都不适合Python 3(在本文发布时已在最新版本上进行了测试)。

这就是你的做法...

import urllib.request

try:
   with urllib.request.urlopen('http://www.python.org/') as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

以上是针对返回“ utf-8”的内容。如果要python“猜测适当的编码”,请删除.decode('utf-8')。

文档:https : //docs.python.org/3/library/urllib.request.html#module-urllib.request


谢谢,原始代码是为Python 2编写的,但是您在此处所做的贡献已得到记录。
海伦·尼利

2

我们可以阅读以下网站html内容:

from urllib.request import urlopen
response = urlopen('http://google.com/')
html = response.read()
print(html)

2
这与@innm的答案相同
PeyM87,18年

1
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
    url:
    data = url.read()

print data

# When the server does not know where the request is coming from.
# Works on python 3.

import urllib.request

user_agent = \
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}

request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data

0

网址应为字符串:

import urllib

link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)           
myfile = f.readline()  
print myfile

11
'和'都是Python中的字符串
Leo

0

我使用以下代码:

import urllib

def read_text():
      quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt")
      contents_file = quotes.read()
      print contents_file

read_text()

0
# retrieving data from url
# only for python 3

import urllib.request

def main():
  url = "http://docs.python.org"

# retrieving data from URL
  webUrl = urllib.request.urlopen(url)
  print("Result code: " + str(webUrl.getcode()))

# print data from URL 
  print("Returned data: -----------------")
  data = webUrl.read().decode("utf-8")
  print(data)

if __name__ == "__main__":
  main()

0
from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen("https://blog.csdn.net/qq_39591494/article/details/83934260").read().decode('utf-8')
print(html)

感谢您提供此代码段,它可能会提供一些有限的即时帮助。通过说明为什么这是一个很好的解决方案,正确的解释将大大提高其长期价值,对于其他存在类似问题的读者来说,这样做将更为有用。请编辑您的答案以添加一些解释,包括您所做的假设。
编码

0

您可以使用requestsbeautifulsoup库来读取网站上的数据。只需安装这两个库并键入以下代码。

import requests
import bs4
help(requests)
help(bs4)

您将获得有关该库所需的所有信息。


help用于查看给定模块/类/功能的文档。我认为这个问题要求一种查看回复内容的方法
Panagiotis Simakis

谢谢,但是这确实是个老问题,已经得到解答。感谢并欢迎您使用stackoverflow。
海伦·尼利
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.