Python 爬虫:专利信息

Python 爬虫:专利信息

解决的主要需求

专利信息来源:
知识产权数据库:点击跳转网站
这个网站原来叫“吉江数据”,最近更名为“知识产权数据库”。在该网站检索前需要注册账号并登录,并且该网站的反爬机制比较完善,如果各位需要爬取的单位地址比较多,建议各位事先多准备几个账号以备使用。

代码

# Author: LSY
import openpyxl
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from bs4 import BeautifulSoup
import random


driver = webdriver.Chrome(executable_path='你的路径')
driver.get('https://www.iprdb.com/user/login.html')
wait = WebDriverWait(driver, 1)
account = driver.find_element_by_css_selector('#account')
account.send_keys("账号名/电话")
password = driver.find_element_by_css_selector('#password')
password.send_keys("密码")
button = driver.find_element_by_css_selector(".login_btnDl")
button.click()
time.sleep(3)
# 登录后会有个通知框,无法通过.click()关闭,最笨的方法是在这里停一下,自己手动关闭
input_add = driver.find_element_by_css_selector("#q")  # 搜索框
submit = driver.find_element_by_css_selector(".search_button")  # 搜索按钮
wb = openpyxl.load_workbook('你的记录文件')
sh = wb.active
n = 0
for j in range(1, sh.max_row+1):
    add = sh['A'+str(j)].value
    input_add.clear()
    input_add.send_keys("ap:"+add)  # "ap:"是该网站的检索式,代表检索申请人
    submit.click()
    time.sleep(random.randint(5, 7))
    try:
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.content')))
        source = driver.page_source
        soup = BeautifulSoup(source, 'lxml')
        list_name = soup.select("ul.patent-bib > li:nth-of-type(8)  span")  # 获取申请人名称
        list_result = soup.select("ul.patent-bib > li:nth-of-type(9)  span")  # 获取相应的申请人地址
        print(list_name)
        print(list_result)
        i = 0
        for i in range(0, len(list_name)):  # 遍历判断
            if list_name[i].text == add:
                sh['B'+str(j)] = list_result[i].text  # 当申请人名称和我们搜索的名称完全一致时,记录在文件中
                print("第", j, '是:', add,  "地址是:", list_result[i].text)
                wb.save('location_nsfc.xlsx')
                break
            else:
                continue
        sh['K' + str(j)] = 101  # 这是我自己的识别code,代表这一行已经爬过了,方便后续检查
    except Exception as e:
        print("第", j, '是:', add, '未查询到地址')
        sh['J'+str(j)] = '未查询到地址'
        wb.save('location_nsfc.xlsx')
    # 登录完成后的搜索框和搜索结果页面的搜索框代码不一致,因此在这里重新定位到搜索框
    input_add = driver.find_element_by_css_selector("#q")  
    submit = driver.find_element_by_css_selector('[type="submit"]')
    n += 1
    if n == 15:
        time.sleep(random.randint(10, 15))  # 每爬取15个就随机的歇一会,尽量避免反爬机制,但是否有用仍是个问号
        n = 0
    else:
        continue

版权声明:本文为nedstark_2012原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。