python应用

以下为爬取一个网址中论文链接,并将其链接内容主干保存到mysql数据库中,

# 导入需要的库文件,若本地没有需要自行下载
import re
import requests
import pymysql
# 连接数据库的参数,主机名,用户名,密码,数据库名称(自行修改)
config={
    "host":"localhost",
    "user":"root",
    "password":"root",
    "database":"pdfmessage"
}
db = pymysql.connect(**config)

cursor = db.cursor()


header1 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39"
}
header2 = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39",
    "Keep-Alive": "false"
}

# 根据网站请求头,返回文本信息
def get_context(url, head):
    web_context = requests.get(url, headers=head)
    return web_context.text

# 含有论文的网站的地址
url = 'https://blog.csdn.net/u014636245/article/details/91426736'
web_context = get_context(url, header1)
# 根据正则表达式筛选出论文的连接
myUrl = re.findall(r'<a href="(.*?..pdf)">', web_context)
print(myUrl)
# 定义论文个数
cnt=1
# 遍历论文的url地址,爬取pdf文档下载到本地,并将一些信息(文章标题,作者,网站地址)存入之前创建的数据库中。
for iurl in myUrl:
    # 根据论文url爬取内容
    web_context = get_context(iurl, header2)
    # 定义正则筛选论文标题、作者等一些信息。
    title1 = re.findall(r"/Title \((.*?)\)", web_context)
    title = re.sub(r'[^a-zA-Z0-9]', '', title1[0])
    print(title)
    producer = re.findall(r"/Producer \((.*?)\)", web_context)
    author = re.findall(r"/Author \((.*?)\)", web_context)
    subject = re.findall(r"/Subject \((.*?)\)", web_context)
    print(f"title:{title}")
    print(f"producer:{producer}")
    print(f"author:{author}")
    print(f"subject:{subject}")
    # 另一种插入数据的方式,通过字符串传入值
    # 定于sql语句,将爬取的内容插入到数据库中。
    sql = "INSERT INTO pdfmessage.paper VALUES(%s,%s,%s,%s,%s,%s)"
    cursor.execute(sql, (cnt,title,producer[0],author[0],subject[0],iurl))
    db.commit()  # 提交数据

    # 将pdf文档存入本地,并且为每一个论文创建了一个txt文件用于存储论文信息。
    # 其中中E:\\CVPR16文件夹需要自己创建,也可以自己指定文件夹
    cnt+=1
    pdfFileName = "E:\\CVPR16\\" + title + '.pdf'
    print(pdfFileName)
    txtFileName = "E:\\CVPR16\\" + title + '.txt'
    print(txtFileName)
    with open(pdfFileName, "w", encoding="utf-8") as f:
        f.write(web_context)

    with open(txtFileName, 'w', encoding="utf-8") as f:
        f.write(f"title:{title1[0]}")
        f.write("\n")
        f.write(f"producer:{producer[0]}")
        f.write("\n")
        f.write(f"author:{author[0]}")
        f.write("\n")
        f.write(f"subject:{subject[0]}")
        f.write("\n")
cursor.close()
db.close()

  

posted on 2022-05-27 08:00  付治齐吖  阅读(53)  评论(0)    收藏  举报