接口协议 Python 网络爬虫实践

jc · 2016年04月19日 · 最后由 大东 回复于 2016年04月19日 · 1155 次阅读

看到社区@raymond写的 Python 网络爬虫,然后自己照着上面实践了一下,抓取了最新发表帖子的前 9 页的帖子的信息,这些信息包括帖子的标题,帖子的发表实践,帖子的发表作者,以及帖子作者的 Testerhome 主页,程序如下:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
from bs4 import BeautifulSoup as bs

f = open("1.html","ab")

str = '''<html>
<head>
<title>最新发布的帖子</title>
<meta charset="utf-8">
</head>
<body>'''

f.write(str)
for i in range(1,10):
    request_url = "https://testerhome.com/topics/last?page=%s" %(i)
    print request_url
    reponse = bs(requests.get(request_url).text,'lxml')
#reponse.find_all('div',{"class":"topic media topic-*"})
    for data in reponse.find_all('div',{"class":"infos media-body"}):
        topic =data.parent.find('div',{"class":"title media-heading"})
        topic_title= topic.find('a')['title']
        topic_link=topic.find('a')['href']
        topic_link='https://testerhome.com/' + topic_link
        topic="帖子的标题为:<a href=" + topic_link + '>'+ topic_title+'</a>'
        #print data_link
        f.write(topic+'<br>')
        topic_author_name=data.parent.find('div',{"class":"info"}).find('a',{"data-author":"true"})['data-name']
        f.write("帖子作者:"+topic_author_name+'<br>')
        topic_public_time= data.parent.find('div',{"class":"info"}).find("span").find("abbr")['title']
        print topic_public_time
        f.write("发表时间:"+topic_public_time+'<br>')
        author_str= "<a href=https://testerhome.com"+(data.parent.find('div',{"class":"info"}).find("a",{"data-author":"true"})["href"]) +">个人主页</a>" 
        print author_str
        f.write(author_str)
        f.write("<hr>")
f.write('</body></html>')

1、感觉这样生成 html 格式有点麻烦,不知大家对这个有没有啥好的办法
2、对于元素的查找个人感觉有点麻烦,不知道除了这个有没有啥更加便捷的办法?
希望大家吐槽

共收到 1 条回复 时间 点赞

MD 语法搞起来.......这代码根本不能看啊☁️

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册