问题描述
彼得·伍德(PeterWood)回答了您的问题。
import urllib.request
uf = urllib.request.urlopen(url)
html = uf.read()
但是,如果要提取数据(例如公司名称,地址和网站),则需要获取HTML源代码并使用HTML解析器对其进行解析。
我建议使用requests
来获取HTML源代码并BeautifulSoup
解析生成的HTML并提取所需的文本。
import requests
from bs4 import BeautifulSoup
link = "https://www.architecture.com/FindAnArchitect/FAAPractices.aspx?display=50"
html = requests.get(link).text
"""If you do not want to use requests then you can use the following code below
with urllib (the snippet above). It should not cause any issue."""
soup = BeautifulSoup(html, "lxml")
res = soup.findAll("article", {"class": "listingItem"})
for r in res:
print("Company Name: " + r.find('a').text)
print("Address: " + r.find("div", {'class': 'address'}).text)
print("Website: " + r.find_all("div", {'class': 'pageMeta-item'})[3].text)
解决方法
例如,网页是链接:
https://www.architecture.com/FindAnArchitect/FAAPractices.aspx?display=50
我必须提供公司名称及其地址和网站。我尝试了以下将html转换为文本的方法:
import nltk
from urllib import urlopen
url = "https://www.architecture.com/FindAnArchitect/FAAPractices.aspx display=50"
html = urlopen(url).read()
raw = nltk.clean_html(html)
print(raw)
但它返回错误:
ImportError: cannot import name 'urlopen