码迷,mamicode.com
首页 > 其他好文 > 详细

爬虫当当网前500书籍

时间:2019-05-08 20:25:46      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:过滤   main   file   asc   信息   result   div   pat   scl   


import requests
import re
import json

def request_dandan(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
    except requests.RequestException:
        return None


def parse_result(html):
    pattern = re.compile(‘<li>.*?list_num.*?(\d+).</div>.*?<img src="(.*?)".*?class="name".*?title="(.*?)">.*?class="star">.*?class="tuijian">(.*?)</span>.*?class="publisher_info">.*?target="_blank">(.*?)</a>.*?class="biaosheng">.*?<span>(.*?)</span></div>.*?<p><span\sclass="price_n">¥(.*?)</span>.*?</li>‘,re.S)
    items = re.findall(pattern,html)
    for item in items:
        yield {
            ‘range‘: item[0],
            ‘iamge‘: item[1],
            ‘title‘: item[2],
            ‘recommend‘: item[3],
            ‘author‘: item[4],
            ‘times‘: item[5],
            ‘price‘: item[6]
        }


def write_item_to_file(item):
    print(‘开始写入数据 ====> ‘ + str(item))
    with open(‘book.txt‘, ‘a‘, encoding=‘UTF-8‘) as f:
        f.write(json.dumps(item, ensure_ascii=False) + ‘\n‘)
        f.close()


def main(page):
    url = ‘http://bang.dangdang.com/books/fivestars/01.00.00.00.00.00-recent30-0-0-1-‘ + str(page)
    html = request_dandan(url)
    items = parse_result(html) # 解析过滤我们想要的信息
    for item in items:
        write_item_to_file(item)


if __name__ == "__main__":
    for i in range(1,26):
        main(i)

  

 

 

爬虫当当网前500书籍

标签:过滤   main   file   asc   信息   result   div   pat   scl   

原文地址:https://www.cnblogs.com/wlswls/p/10834192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!