【发布时间】:2012-03-27 22:01:14
【问题描述】:
我有一个 URL 列表,我想从中获取属性。 Python新手,请见谅。 Windows 7,64 位。 Python 3.2。
以下代码有效。 pblist 是一个由包含键 'short_url' 的 dicts 组成的列表。
for j in pblist[0:10]:
base_url = j['short_url']
if hasattr(BeautifulSoup(urllib.request.urlopen(base_url)), 'head') and \
hasattr(BeautifulSoup(urllib.request.urlopen(base_url)).head, 'title'):
print("Has head, title attributes.")
try:
j['title'] = BeautifulSoup(urllib.request.urlopen(base_url)).head.title.string.encode('utf-8')
except AttributeError:
print("Encountered attribute error on page, ", base_url)
j['title'] = "Attribute error."
pass
以下代码没有 - 例如,代码声称 BeautifulSoup 对象没有 head 和 title 属性。
for j in pblist[0:10]:
base_url = j['short_url']
page = urllib.request.urlopen(base_url)
if hasattr(BeautifulSoup(page), 'head') and \
hasattr(BeautifulSoup(page).head, 'title'):
print("Has head, title attributes.")
try:
j['title'] = BeautifulSoup(urllib.request.urlopen(base_url)).head.title.string.encode('utf-8')
except AttributeError:
print("Encountered attribute error on page, ", base_url)
j['title'] = "Attribute error."
pass
为什么?在 BeautifulSoup 中将 url 传递给 urllib.request.urlopen 和传递 urllib.request.urlopen 返回的 HTTPResponse ojbect 有什么区别?
【问题讨论】:
标签: python url beautifulsoup