【Python】学习笔记总结7(简单爬虫)
生活随笔
收集整理的這篇文章主要介紹了
【Python】学习笔记总结7(简单爬虫)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 七、Python簡單爬蟲
- 1.重要知識與技能
- 2.使用re表達式抓取網頁文件
- 3.使用requests抓取網頁
- 4.使用re正則表達式提取數據
- 5.使用xPath工具提取數據
- 6.使用BeautifulSoup工具
七、Python簡單爬蟲
1.重要知識與技能
重要知識與技能:
2.使用re表達式抓取網頁文件
import re myFile = open('Index.html','r',encoding='UTF-8') myContent = myFile.read() myFile.close() #myPatten = "<li>(.*)</li>" myPatten2 = "([a-zA-Z0-9_\.-]+@[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+)" mylist = re.findall(myPatten2,myContent) print(mylist)3.使用requests抓取網頁
import requests myURL = 'https://www.3dmgame.com' myContent = requests.get(myURL).content.decode('UTF-8')4.使用re正則表達式提取數據
def Get3DMNews_WithRE():'''得到3DM網站的新聞內容:return: 獲取的新聞內容'''import requestsimport remyURL = 'https://www.3dmgame.com'myContent = requests.get(myURL).content.decode('UTF-8')myPartten = '<a href="(.*)" target="_blank" >(.*)</a>\n <span>(.*)</span>'myList = re.findall(myPartten,myContent)for item in myList :myNews = {}myNews['title'] = item[0]myNews['herf'] = item[1]myNews['time'] = item[2]print(myNews)passpass5.使用xPath工具提取數據
def Get3DMNews_WithXPATH():'''得到3DM網站的新聞內容:return: 獲取的新聞內容'''import requestsfrom lxml import htmlmyURL = 'https://www.3dmgame.com'myContent = requests.get(myURL).content.decode('UTF-8')etree = html.etreeeTreeHtml = etree.HTML(myContent)myList = eTreeHtml.xpath("//li")for item in myList :myNews = {}myNews['title'] = item.xpath('./a')[0].textmyNews['herf'] = item.xpath('./a/@href')[0]myNews['time'] = item.xpath('./span')[0].textprint(myNews)passpass6.使用BeautifulSoup工具
def Get3DMNews_WithBeautifulSoup():'''得到3DM網站的新聞內容:return: 獲取的新聞內容'''import requestsfrom bs4 import BeautifulSoupmyURL = 'https://www.3dmgame.com'myContent = requests.get(myURL).content.decode('UTF-8')bsHtml = BeautifulSoup(myContent,'html5lib')myList = bsHtml.find_all('div')[10].find_all('div')[8].find_all('div')[91].find_all('li')for item in myList :myNews = {}myNews['title'] = item.find('a').get_text()myNews['herf'] = item.find('a').get('href')myNews['time'] = item.find('span').get_text()print(myNews)passpass總結
以上是生活随笔為你收集整理的【Python】学习笔记总结7(简单爬虫)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】学习笔记总结(第一阶段(
- 下一篇: 【Python】学习笔记总结8(经典算法