【问题标题】:What is wrong with this code for web crawler?网络爬虫的这段代码有什么问题?
【发布时间】:2013-08-15 12:25:55
【问题描述】:

所以,我基本上想做的是,找到特定页面的链接(此处为 10)。一切正常,我什至可以正确获取索引(startlink、startquote、endquote)。但是,URL 没有打印出来。为什么?而且,出了什么问题?如果你能纠正它,我会很高兴!

def web():
n=0
a=open('quora.txt', 'r') #I've saved it as a txt file in my system
b=a.read()
startlink=0
while(n<10):
    startlink=b.find('<a href=', startlink+1)
    startquote=b.find('"', startlink)
    endquote=b.find('"', startquote)
    url=b[startquote+1:endquote]
    print url, startlink, startquote, endquote
    n=n+1

这是我得到的输出,只有索引。不,网址

4506 4514 4514
5308 5316 5316
5357 5365 5365
5472 5480 5480
5515 5523 5523
5588 5596 5596
5639 5647 5647
5723 5731 5731
6828 6836 6836
6867 6875 6875

【问题讨论】:

    标签: python python-2.7 web web-crawler


    【解决方案1】:

    endquote 的搜索应该在 startquote 的位置后一个字符开始:

    def web():
        n = 0
        a = open('quora.txt', 'r') #I've saved it as a txt file in my system
        b = a.read()
        startlink = 0
        while (n < 10):
            startlink = b.find('<a href=', startlink + 1)
            startquote = b.find('"', startlink)
            endquote = b.find('"', startquote + 1)
            url = b[startquote + 1:endquote]
            print url, startlink, startquote, endquote
            n = n + 1
    

    因为现在它也与 endquote 匹配相同的 startquote

    【讨论】:

    • 我尝试对代码进行一些改进。和。写了这个。但是,我发现并非所有链接都被检查/打印。 def get_next_target(page): startlink=page.find('name__=='__main' 则中断打印链接:get_all_links(page)
    • 那么您在页面上查找链接的方法很容易被破坏,html 很难解析。如果&lt;a href 有两个空格而不是一个怎么办?使用损坏的 html 或格式奇怪的 html,它肯定可能找不到页面上的所有链接。您应该检查一个 html 解析器库,例如 lxml ..
    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多