会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
Python 全系列/第十五阶段:Python 爬虫开发/爬虫基础(旧) 856楼

from fake_useragent import UserAgent
import requests
from lxml import etree  #解析库


def get_html(url):
    '''
    param url:要爬取的地址
    return:返回html
    '''

    headers={"User-Agent":UserAgent().chrome}
    resp=requests.get(url,headers=headers) #发送请求
    if resp.status_code ==200:
        resp.encoding='utf-8'  #设置字符集
        return resp.text
    else:
        return None

def parse_list(html):
    '''
    param url:传递进来一个有电影列表的html
    return:返回一个电影列表的url
    '''
    # if html:    #html在有值的情况下在做解析
    e=etree.HTML(html)
    list_url=['http://maoyan.com{}'.format(url) for url in e.xpath('//div[@class="movie-item-hover"]/a/@href')]
    return list_url

def pares_index(html):
    '''
    param url:传递进来一个有电影具体信息的html
    return:提取好的电影具体信息
    '''
    e = etree.HTML(html)
    name = e.xpath('//h1[@class="name"]/text()')
    type = e.xpath('//li[@class="ellipsis"][1]/a/text()')
    content = e.xpath('//span[@class="dra"]/text()')

    return {"name":name,"type":type,"content":content}

#     actors=e.xpath('')
#     actors=format_data(actors)

# 有重复的演员名字,需要去重
# def format_data(actors):
#     actor_set=set()
#     for actor in actors:
#         actor_set.add(actor.strip())  #strip去空格
#         return actor_set

def main():

    '''控制上述方法的实施,分配相应的url'''
    num = int(input('请输入多少页:'))
    for page in range(num):
        url="https://maoyan.com/films?showType=1&offset={}".format(page*30)

        list_html=get_html(url)  #发送请求
        list_url=parse_list(list_html)  #解析list_html,返回list_url每个电影的信息
        for url in list_url:
            info_html=get_html(url)
            movie = pares_index(info_html)
            print(movie)

if __name__ =='__main__':
    main()

老师,这个代码只运行到请输入多少页,然后就运行结束了。哪里出错了?

Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 857楼
Python 全系列/第十五阶段:Python 爬虫开发/docker容器扩展-旧20230925 861楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫基础 863楼

from urllib.request import Request,build_opener,HTTPCookieProcessor
from urllib.parse import urlencode  #转换用的
from fake_useragent import UserAgent
from http.cookiejar import MozillaCookieJar#保存cookie得文件需要引进的模块

def get_cookie():
    login_url='http://learn.open.com.cn/Account/Login'#登录网站的url
    from_data={
        "user": "jxt17703612482",
        "password": "JXTjxt00"
    }
    headers={"UserAgent":UserAgent().random}
    rep=Request(login_url, headers=headers, data=urlencode(from_data).encode())

    cookie_jar=MozillaCookieJar()#保存cookie
    handler=HTTPCookieProcessor(cookie_jar)#参数cookie
    opener=build_opener(handler)
    resp=opener.open(rep)
    cookie_jar.save('cookie.txt',ignore_discard=True,ignore_expires=True)#【!】保存cookie,在cookie.txt文件夹里

def use_cookie():
    info_url='http://learn.open.com.cn/StudentCenter/MyCourse/MyCourseDetail?CourseID=69249&CourseIndex=0'#登录个人中心的url
    headers = {"UserAgent": UserAgent().random}
    rea=Request(info_url,headers=headers)
    cookie_jar=MozillaCookieJar()
    cookie_jar.load('cookie.txt',ignore_discard=True,ignore_expires=True)#加载用cookie_jar.load
    handler=HTTPCookieProcessor(cookie_jar)
    opener=build_opener(handler)
    resp=opener.open(rea)
    print(resp.read().decode())


if __name__ == '__main__':
    get_cookie()
    # use_cookie()

老师,我这显示以下错误,上面是我得代码。我搞了一个多小时了,也没整明白,你帮我看看。

D:\pythonDownloads\python.exe E:/demo1/test12/pdemo/15cookie的使用3.py

Traceback (most recent call last):

  File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 34, in <module>

    get_cookie()

  File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 18, in get_cookie

    resp=opener.open(rep)

  File "D:\pythonDownloads\lib\urllib\request.py", line 531, in open

    response = meth(req, response)

  File "D:\pythonDownloads\lib\urllib\request.py", line 641, in http_response

    'http', request, response, code, msg, hdrs)

  File "D:\pythonDownloads\lib\urllib\request.py", line 569, in error

    return self._call_chain(*args)

  File "D:\pythonDownloads\lib\urllib\request.py", line 503, in _call_chain

    result = func(*args)

  File "D:\pythonDownloads\lib\urllib\request.py", line 649, in http_error_default

    raise HTTPError(req.full_url, code, msg, hdrs, fp)

urllib.error.HTTPError: HTTP Error 403: Forbidden


Process finished with exit code 1


Python 全系列/第十五阶段:Python 爬虫开发/scrapy框架使用(旧) 866楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫基础 867楼

老师,麻烦帮忙看一下我的代码:

源码:

作业_爬取拉钩职位.zip

运行结果中不能爬取到所有页面

image.png

另外保存的结果中有太多空格和\n

image.png

麻烦老师协助解决下,谢谢!





Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 868楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637