会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132647个问题

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框架使用(旧) 872楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础 873楼

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

源码:

作业_爬取拉钩职位.zip

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

image.png

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

image.png

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





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

1699963864197.jpg

Python 全系列/第十六阶段:Python 爬虫开发/scrapy框架使用 877楼

之前用request爬取猫眼电影时,

由于猫眼把电影信息变成了动态获取,因此无法直接用源代码爬取。

现在通过selenium直接点进电影信息时发现,

即使首页面加了防检测,但只能在当前页面生效,打开的新页面window.navigator.wevdrive===True,依旧无法获取电影信息,因此仍无法用selenium获取多条电影信息。

因此通过request爬取电影目录,selenium爬取电影信息,总算是成功爬取了电影信息,目前猫眼评分转了码问题仍未解决

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from time import sleep
import requests
from fake_useragent import UserAgent
from lxml import etree
from queue import Queue
from threading import Thread


def get_film_list(page):
    film_list = []
    for i in range(page):
        url = f'https://www.maoyan.com/films/?showType=3&offset={30*i}'
        headers = {'User-Agent': UserAgent().chrome}
        resp = requests.get(url, headers = headers)
        html = etree.HTML(resp.text)
        films = html.xpath('//dd/div[@title]/a/@href')
        for film in films:
            film_list.append(film)
        sleep(1)
    return film_list


def get_film_data(film):
    url = f'https://www.maoyan.com{film}'
    options = webdriver.ChromeOptions()
    # 设置无头
    options.add_argument('--headless')
    # 防检测1
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)

    service = Service(executable_path='./tools/chromedriver')
    chrome = webdriver.Chrome(service=service, options=options)
    chrome.implicitly_wait(2)

    # 防检测2
    chrome.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
            Object.defineProperty(navigator, 'webdriver', {
              get: () => false
            })
          """
    })

    chrome.get(url)
    name = chrome.find_element(By.XPATH, '//h1[@class="name"]').text
    type_ = [i.text for i in chrome.find_elements(By.XPATH, '//a[@class="text-link"]')]
    chrome.find_element(By.XPATH, '//div[@class="tab-title "]').click()
    actors = []
    for i in chrome.find_elements(By.XPATH, '//li[@class="celebrity actor"]/div/a'):
        if i.text and i.text not in actors:
            actors.append(i.text.strip())

    info = {'电影名': name, '类型': type_, '主演': actors}
    return info


def create_quere(list):
    q = Queue()
    for i in list:
        q.put(i)
    return q


class MyThread(Thread):
    def __init__(self, q):
        Thread.__init__(self)
        self.__q = q

    def run(self) -> None:
        while not self.__q.empty():
            film = self.__q.get()
            film_info = get_film_data(film)
            print(film_info)


if __name__ == '__main__':
    film_list = get_film_list(1)
    q = create_quere(film_list)
    for i in range(3):
        t = MyThread(q)
        t.start()


Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 878楼

mongo.zip

老师,我这个代码可以运行,但是数据不能够保存到mongo数据库中,这是为什么呢?


Python 全系列/第十六阶段:Python 爬虫开发/爬虫数据存储 879楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫反反爬- 881楼
Python 全系列/第十六阶段:Python 爬虫开发/scrapy框架使用 882楼

代码:

import scrapy


class BizhizuSpider(scrapy.Spider):
    name = 'bizhizu'
    allowed_domains = ['bizhizu.cn']
    # start_urls = ['https://www.bizhizu.cn/pic/7097.html']
    start_urls=['https://www.bizhizu.cn/pic/7097-0.html']

    def parse(self, response):
        image_url=response.xpath('//div[@class="pic"]/a[@id="photoimg"]/img/@src').extract_first()
        print(image_url)
        image_name=response.xpath('string(//div[@class="txt"]/h1)').extract_first()
        print(image_name)
        yield{
            "image_url":image_url,
            "image_name":image_name
        }
        next_url=response.xpath('//div[@class="photo_next"]//a/@href').extract_first()
        yield scrapy.Request(next_url,callback=self.parse)
from scrapy.pipelines.images import ImagesPipeline
from scrapy import Request
class PicturePipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        yield Request(item["image_url"],meta={"name":item["image_name"]})
    def file_path(self, request, response=None, info=None,*,item=None):
        name=request.meta["name"].strip()
        name=name.replace("/","_")
        return name+'.jpg'

运行结果:

屏幕截图 2021-03-19 184131.png老师请问一下,为什么我在爬取淘女郎图片的时候,每次爬取的图片名称都是一样的,但是image_url是不同的,麻烦老师帮我看看程序哪里出问题了?

Python 全系列/第十六阶段:Python 爬虫开发/scrapy 框架高级 884楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础 885楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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