Ответ 1
Это работает в Python 2.x.
Для Python 3 смотрите в документах:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
Я пытаюсь использовать Python для загрузки исходного кода HTML сайта, но получаю эту ошибку.
Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py", line 3, in <module>
file = urllib.urlopen("http://www.python.org")
AttributeError: 'module' object has no attribute 'urlopen'
Я следую инструкциям здесь: http://www.boddie.org.uk/python/HTML.html
import urllib
file = urllib.urlopen("http://www.python.org")
s = file.read()
f.close()
#I'm guessing this would output the html source code?
print(s)
Я использую Python 3.
Это работает в Python 2.x.
Для Python 3 смотрите в документах:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
Совместимое с Python 2 + 3 решение:
import sys
if sys.version_info[0] == 3:
from urllib.request import urlopen
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlopen
# Your code where you can use urlopen
with urlopen("http://www.python.org") as url:
s = url.read()
print(s)
import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)
В Python v3 "urllib.request" является модулем сам по себе, поэтому "urllib" здесь нельзя использовать.
Чтобы заставить 'dataX = urllib.urlopen (url).read()' работать в Python 3 (это было бы правильно для Python 2), вам нужно просто изменить 2 мелочи.
1: Сам оператор urllib (добавьте .request посередине):
dataX = urllib.request.urlopen(url).read()
2: оператор импорта, предшествующий ему (смените "import urlib" на:
import urllib.request
И это должно работать в python3 :)
import urllib.request as ur
filehandler = ur.urlopen ('http://www.google.com')
for line in filehandler:
print(line.strip())
Для Python 3 попробуйте что-то вроде этого:
import urllib.request
urllib.request.urlretrieve('http://crcv.ucf.edu/THUMOS14/UCF101/UCF101/v_YoYo_g19_c02.avi', "video_name.avi")
Это загрузит видео в текущий рабочий каталог
Решение для python3:
from urllib.request import urlopen
url = 'http://www.python.org'
file = urlopen(url)
html = file.read()
print(html)
ваш код, используемый в python2.x, вы можете использовать так:
from urllib.request import urlopen
urlopen(url)
кстати, предложите другую модель, называемую запросы, более удобную в использовании, вы можете использовать pip установить ее и использовать так:
import requests
requests.get(url)
requests.post(url)
Я думал, что это легко использовать, я тоже начинающий.... хахах
Один из возможных способов сделать это:
import urllib
...
try:
# Python 2
from urllib2 import urlopen
except ImportError:
# Python 3
from urllib.request import urlopen
import urllib
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.newegg.com/") as url:
s = url.read()
print(s)
soup = BeautifulSoup(s, "html.parser")
all_tag_a = soup.find_all("a", limit=10)
for links in all_tag_a:
#print(links.get('href'))
print(links)