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

from fake_useragent import UserAgent
import requests
from lxml import etree
from time import sleep


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 html: 传递进来一个有电影列表的html
    :return: 返回一个电影列表的url
    '''

    e = etree.HTML(html)
    list_url = ['http://maoyan.com{}'.format(url) for url in e.xpath('//div[@class="movie-item film-channel"]/a/@href')]
    return list_url


def pares_index(html):
    '''
    :param html: 传递进来一个有电影信息的html
    :return: 已经提取好的电影信息
    '''
    e = etree.HTML(html)
    name = e.xpath('//h1[@class="name"]/text()')
    type = e.xpath('//li[@class="ellipsis"]/a[1]/text()')
    actors = e.xpath('//div[@class="celebrity-group"][2]/ul[@class="celebrity-list clearfix"]/li/div/a/text()')
    actors = format_data(actors)
    return {"name": name, "type": type, "actors": actors}


def format_data(actors):
    actor_set = set()
    for actor in actors:
        actor_set.add(actor.strip())
    return actor_set


def main():
    num = int(input('请输入要获取多少页:'))
    for page in range(num):
        url = 'http://maoyan.com/films?showType=3&offset={}'.format(page*30)
        list_html = get_html(url)
        list_url = parse_list(list_html)

        for url in list_url:
            info_html = get_html(url)
            movie = pares_index(info_html)
            print(movie)


if __name__ == '__main__':
    main()

运行的时候没有反应

image.png

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

image.png

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
	at org.mybatis.generator.internal.db.ConnectionFactory.getConnection(ConnectionFactory.java:68)
	at org.mybatis.generator.config.Context.getConnection(Context.java:526)
	at org.mybatis.generator.config.Context.introspectTables(Context.java:436)
	at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:222)
	at org.mybatis.generator.api.MyBatisGenerator.generate(MyBatisGenerator.java:133)
	at GeneratorSqlmap.generator(GeneratorSqlmap.java:27)
	at GeneratorSqlmap.main(GeneratorSqlmap.java:33)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2120)
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2143)
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310)
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
	... 10 more

我运行的时候就这个样子了,我的数据库是8的,jar包也换了。

JAVA 全系列/第六阶段:项目管理与SSM框架/Mybatis 21440楼

老师,我在使用多线程爬取文件的时候,会出现文件写入不全,然后我在写入文件的的时候加入锁,但是发现还写入不全,您帮我看一下!

from threading import Thread,Lock
import requests
from lxml import etree
from fake_useragent import UserAgent
from queue import Queue
class Spider(Thread):
    def __init__(self,url_queue,lock):
        Thread.__init__(self)
        self.url_queue = url_queue
        self.lock = lock

    def run(self):
        while not self.url_queue.empty():
            url = self.url_queue.get()
            print(url)
            headers = {'User-Agent':UserAgent().chrome}
            resp = requests.get(url,headers=headers)
            e = etree.HTML(resp.text)
            contents = [div.xpath('string(.)').strip() for div in e.xpath('//div[@class="content"]')]
            #加入锁
            self.lock.acquire()
            with open('qiushi.text', 'a', encoding='utf-8')as f:
                for content in contents:
                    f.write(content+'\n')
            self.lock.release()
if __name__ == '__main__':
    base_url = 'https://www.qiushibaike.com/text/page/{}/'
    lock = Lock()
    url_queue = Queue()
    for num in range(1,14):
        url_queue.put(base_url.format(num))
    for i in range(6):
        spider = Spider(url_queue,lock)
        spider.start()


Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 21445楼
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 21446楼

from sqlalchemy import create_engine, Column, String, Integer, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
import time

USERNAME = 'root'
PASSWORD = '19991108ljf'
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'first_sqlalchemy'

DB_URL = 'mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset=utf8'\
    .format(user=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, db=DATABASE)

engine = create_engine(DB_URL)
Base = declarative_base(engine)
session = sessionmaker(engine)()


# 排序方式1:定义模型时指定模型方式
class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    create_time = Column(DateTime, nullable=False, default=datetime.now)
    __mapper_args__ = {
        # 正序
        # 'order_by': create_time
        # 倒叙
        "order_by": create_time.desc()
    }

    def __repr__(self):
        return '<Article(title:%s,create_time:%s)>' % (self.title, self.create_time)


def add_data():
    Base.metadata.drop_all()
    Base.metadata.create_all()
    article_1 = Article(title='title_1')
    session.add(article_1)
    session.commit()
    time.sleep(3)
    article_2 = Article(title='title_2')
    session.add(article_2)
    session.commit()


def oper():
    # 不用再指定排序方式  因为在定义模型的时候  就已指定好排序方式
    articles_2 = session.query(Article).all()
    print(articles_2)


if __name__ == '__main__':
    add_data()
    # oper()

老师,我这串代码报错,提示我得到意外参数‘order_by’怎么解决

屏幕截图 2021-05-16 155911.png

Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/Flask数据库 21450楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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