加入网址抛出异常

时间:2015-05-09 15:38:52

标签: python web-scraping urllib

我有两个变量,一个包含绝对URL,另一个包含另一个部分的相对路径。首先,我尝试了一个简单的连接。

absolute_url = www.example.com
relative_url = /downloads/images
url = absolute_url + relative_url

当我打印url变量时,我有一个格式正确的URL。但是当我尝试使用请求或urllib2来检索数据时,大约有一半的时间会抛出异常:' NoneType'对象没有属性' getitem '

然后我研究并认为也许我应该使用urllib.urlparse.urljoin()来做到这一点,但我仍然得到错误。

但令我感到有趣的是,有时候它有效,有时候不会。关于这里发生了什么的任何想法?

修改

以下是实际代码:

url = "http://www.hdwallpapers.in"
html = requests.get(url)
soup = BeautifulSoup(html.text)

categories = ("Nature", "Animals & Birds", "Beach", "Bikes", "Cars","Dreamy & Fantasy", "Others", "Travel & World")
random_category = random.randint(0, len(categories)) - 1
selected_category = categories[random_category]
selected_category_url = soup.find('a', text=selected_category)

category_page_url_join = urlparse.urljoin(url, selected_category_url['href'])
category_page_html = requests.get(category_page_url_join)

1 个答案:

答案 0 :(得分:1)

您有一个categories的列表:

categories = ("Nature", "Animals & Birds", "Beach", "Bikes", "Cars","Dreamy & Fantasy", "Others", "Travel & World")

然后你随机挑选一个并搜索它:

random_category = random.randint(0, len(categories)) - 1
selected_category = categories[random_category]
selected_category_url = soup.find('a', text=selected_category)

这将更容易编写,并且可读如下:

selected_category_url = soup.find('a', text=random.choice(categories))

现在你的问题无疑来自:

category_page_url_join = urlparse.urljoin(url, selected_category_url['href'])

这意味着您的selected_category_url结束了None,因为您soup.find实际上找不到任何内容。因此,实际上您正在尝试运行None['href'](当然会失败......)

请注意,requests不会进行任何HTML实体转义,但BeautifulSoup会尽力尝试,例如:

from bs4 import BeautifulSoup
soup1 = BeautifulSoup('smith & jones')
soup2 = BeautifulSoup('smith & jones')
soup1, soup2
(<html><body><p>smith &amp; jones</p></body></html>,
 <html><body><p>smith &amp; jones</p></body></html>)

所以,既然你说&#34;大约一半的时间&#34;然后是因为你有3个选择,你正在寻找那场不匹配....尝试用你的&取代categories { {1}}而不是。

相关问题