鱼C论坛

 找回密码
 立即注册
查看: 510|回复: 1

python爬取评论时出错

[复制链接]
发表于 2018-8-27 17:20:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 chunguang 于 2018-8-27 17:41 编辑

python爬取评论,但只能爬取每一页的第一条评论,求大神
import requests
import re
import csv
from bs4 import BeautifulSoup
from requests.exceptions import  RequestException
from urllib.parse import  urlencode
from multiprocessing import Pool

def get_comments(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
        }
        response=requests.get(url,headers=headers)
        response.encoding = 'gbk'
        if response.status_code==200:
            return response.text
        print('请求评论错误')
        return None
    except RequestException:
        return None


def parse_comments(html):
    soup = BeautifulSoup(html, 'lxml')
    items=soup.find_all('body')
    for item in items:
        name = item.select('.username ')[1].text
        rank = item.select('#commentnormalinfo a')[0].text
        comments = item.select('.commenttext')[0].text
        province = item.select('.commentinfo span')[3].text
        price = item.select('.price_num')[0].text
        data={
            'name':name,
            'rank':rank,
            'comments': comments,
            'province': province,
            'price': price
        }
        yield data

def main():
    url = 'http://www.yanyue.cn/product/comments/148?paramsend=postget&productid=148¶msend=postget&page_offset=1'
    html=get_comments(url)
    for item in parse_comments(html):
        print(item)

if __name__=='__main__':
    main()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-8-28 09:02:28 | 显示全部楼层
兄弟,你的解析库使用的有问题,你识别的是所有的body,一个网页中只有一个body,所以你的items 中只有一个元素,当然就只把每一页的第一条评论搞出来了,建议你要是按照标签找的话,先找这个:<ul class="mt10"> 然后再找li的标签。good luck
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-6 16:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表