我正在尝试获取所有文章的链接(碰巧有“title may blank”类来表示它们)。我试图弄清楚为什么下面的代码在运行时会生成一大堆“href=”,而不是返回实际的URL。在失败的25篇文章url(all'href=')之后,我还得到了一堆随机文本和链接,但不确定为什么会发生这种情况,因为它应该在停止查找类'title may blank'之后停止。你们能帮我找出哪里不对劲吗?你知道吗
import urllib2
def get_page(page):
response = urllib2.urlopen(page)
html = response.read()
p = str(html)
return p
def get_next_target(page):
start_link = page.find('title may-blank')
start_quote = page.find('"', start_link + 4)
end_quote = page.find ('"', start_quote + 1)
aurl = page[start_quote+1:end_quote] # Gets Article URL
return aurl, end_quote
def print_all_links(page):
while True:
aurl, endpos = get_next_target(page)
if aurl:
print("%s" % (aurl))
print("")
page = page[endpos:]
else:
break
reddit_url = 'http://www.reddit.com/r/worldnews'
print_all_links(get_page(reddit_url))
Rawing是正确的,但是当我面对一个XY problem时,我更喜欢提供完成} 的HTML解析器来解析网页:
X
的最佳方法,而不是修复Y
的方法。您应该使用类似^{如果您真的对HTML解析器过敏,至少使用regex(即使您应该坚持使用HTML解析):
那是因为
不是你想的那样。 开始链接设置为“标题可以空白”的索引。所以,如果你第页。查找在start_link+4,您实际上开始搜索“e may blank”。 如果你改变了
至
会有用的。你知道吗
相关问题 更多 >
编程相关推荐