例如,网页是链接:
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
答案 0 :(得分:6)
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)