需求:
工作中需要计算上市公司绿色专利申请数据,需要从先搜索表单值,然后进行匹配和请求,最后需要分析汇总,用于后续的深度数据挖掘。
解决:
python中的三大插件,即requests、Beautifulsoup4、lxml的灵活运用,可直接对表单值进行提取、匹配,并进行统计分析
import requests from bs4 import BeautifulSoup def getHTMLText(url): try: r = requests.get(url, timeout = 30) r.raise_for_status() #r.encoding = 'utf-8' return r.text except: return "" def getContent(url): html = getHTMLText(url) # print(html) soup = BeautifulSoup(html, "html.parser") title = soup.select("div.hd > h1") print(title[0].get_text()) time = soup.select("div.a_Info > span.a_time") print(time[0].string) author = soup.select("div.qq_articleFt > div.qq_toolWrap > div.qq_editor") print(author[0].get_text()) paras = soup.select("div.Cnt-Main-Article-QQ > p.text") for para in paras: if len(para) > 0: print(para.get_text()) print() #写入文件 fo = open("text.txt", "w+") fo.writelines(title[0].get_text() + "\n") fo.writelines(time[0].get_text() + "\n") for para in paras: if len(para) > 0: fo.writelines(para.get_text() + "\n\n") fo.writelines(author[0].get_text() + '\n') fo.close() #将爬取到的文章用字典格式来存 article = { 'Title' : title[0].get_text(), 'Time' : time[0].get_text(), 'Paragraph' : paras, 'Author' : author[0].get_text() } print(article) def main(): url = "http://news.qq.com/a/20170504/012032.htm" getContent(url); main()
数据来源: 上市公司绿色专利申请数据