Crawler only loads one title

*爱你&永不变心* 提交于 2019-12-13 03:37:13

问题


i did some questions in here and them one guy gave me this code. But I need help because it is only bringing one result of my websites.txt

Crawler.py

import urllib.request
import re

regex = "<title>(.+?)</title>"
pattern = re.compile(regex)
txtfl = open('websites.txt')
webpgsinfile = txtfl.readlines()
urls = webpgsinfile
htmlfile = urllib.request.urlopen(urls[i])
htmltext = htmlfile.read().decode('utf8')
titles = re.findall(pattern,htmltext)

if len(titles) > 0:
    print(titles[0])
    i+=1

The websites.txt

http://youtube.com
http://bigsolutions.com.br

回答1:


import re
from urllib.request import urlopen

def get_page(url, encoding='utf-8'):
    return urlopen(url).read().decode(encoding, errors='ignore')

def get_title(txt, reg=re.compile('<title>(.*)</title>', re.IGNORECASE | re.DOTALL)):
    match = reg.search(txt)
    if match is None:
        return ''
    else:
        return match.group(1).strip()

def main():
    with open('websites.txt') as inf:
        urls = [line.strip() for line in inf]
    titles = [get_title(get_page(url)) for url in urls if url]
    print(titles)

if __name__=="__main__":
    main()

results in

["LimeCD - Lime's Code Library", 'YouTube', 'Big Solutions - Aqui nós pensamos grande!']



回答2:


I'm still a python2 programmer, so forgive any errors because of that. Also note that this code is untested and it's just for you to get a feeling of what you need to do.

import urllib.request
import re

regex = "<title>(.+?)</title>" 
pattern = re.compile(regex)
urls = open('websites.txt').readlines()

titles = []
for url in urls:
    htmlfile = urllib.request.urlopen(url)
    htmltext = htmlfile.read().decode('utf8')
    titles.append(re.findall(pattern, htmltext))
print(titles)

What this does is it creates an array of the titles you want, and then iterates through your urls and adds the title to the titles array. I don't see how the original code compiled, but it looked like it was missing a loop.



来源:https://stackoverflow.com/questions/20308357/crawler-only-loads-one-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!