ฉันจะอ่านเนื้อหาของ URL ด้วย Python ได้อย่างไร


93

ต่อไปนี้ใช้งานได้เมื่อฉันวางบนเบราว์เซอร์:

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

แต่เมื่อฉันลองอ่าน URL ด้วย Python ไม่มีอะไรเกิดขึ้น:

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

ฉันต้องเข้ารหัส URL หรือไม่หรือมีบางอย่างที่ฉันไม่เห็น

คำตอบ:


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 หรือภายในคำถามนี้: 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

ฉันยังแนะนำและสนับสนุนให้โปรแกรมเมอร์ใช้requestsโมดูลแบรนด์ใหม่การใช้งานกับ Pythonic Code มากขึ้น
Hans Zimermann

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'ดูเหมือนว่าไม่มีฟังก์ชัน urlopen ใน python 3.5 เปลี่ยนชื่อแล้วหรือยัง? แก้ไข: ตัวอย่างคำตอบด้านล่างแก้:from urllib.request import urlopen
LMD

@ user7185318 ใช่ใน Python 3 urlibแพคเกจเห็นการปรับโครงสร้างใหม่และการเปลี่ยนแปลง API ฉันจะอัปเดตคำตอบเพื่อเน้นย้ำใน Python 2
woozyking

จะเกิดอะไรขึ้นหากลิงค์ที่ให้มาขอชื่อผู้ใช้และรหัสผ่าน? แล้วรหัสจะเปลี่ยนได้อย่างไร?
Dr. Essen

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แต่คิดว่าอาจช่วยประหยัดเวลาได้


นี่ไม่ใช่วิธีที่ดีที่สุดในการอ่านข้อมูลจาก url โดยใช้ python3 เนื่องจากพลาดประโยชน์ของคำสั่ง 'with' ดูคำตอบของฉัน: stackoverflow.com/a/56295038/908316
Jared

ไม่สิ่งนี้จะไม่ทำงานในขณะที่วนซ้ำ โทรครั้งเดียวเท่านั้น ซึ่งถ้าคุณถามฉัน
lone_coder

11

โซลูชันที่ทำงานร่วมกับ 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' ลบ. ถอดรหัส ('utf-8') หากคุณต้องการให้ python "เดาการเข้ารหัสที่เหมาะสม"

เอกสารประกอบ: https://docs.python.org/3/library/urllib.request.html#module-urllib.request


ขอบคุณโค้ดต้นฉบับเขียนขึ้นสำหรับ Python 2 แต่การมีส่วนร่วมของคุณได้รับการบันทึกไว้ที่นี่
Helen Neely

2

เราสามารถอ่านเนื้อหา html ของเว็บไซต์ได้ดังนี้:

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

2
นี่คือคำตอบจาก @innm
PeyM87

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

URL ควรเป็นสตริง:

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

คุณสามารถใช้requestsและbeautifulsoupไลบรารีเพื่ออ่านข้อมูลบนเว็บไซต์ เพียงติดตั้งไลบรารีทั้งสองนี้และพิมพ์รหัสต่อไปนี้

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

คุณจะได้รับข้อมูลทั้งหมดที่คุณต้องการเกี่ยวกับห้องสมุด


helpใช้เพื่อดูเอกสารของโมดูล / คลาส / ฟังก์ชันที่กำหนด ฉันคิดว่าคำถามนั้นขอวิธีดูเนื้อหาของคำตอบ
Panagiotis Simakis

ขอบคุณ แต่นี่เป็นคำถามเก่าจริงๆและได้รับคำตอบแล้ว ขอขอบคุณและยินดีต้อนรับสู่ stackoverflow
Helen Neely
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.