python lxml.html Beautifulsoup 打开 本地html 文件方法

python 打开 本地html 文件方法,lxml BS4 open  local .html file

REF:

https://docs.python-guide.org/scenarios/scrape/

https://www.datacamp.com/community/tutorials/python-xml-elementtree

1 lxml.html 

from lxml import html,etree
import requests

from bs4 import BeautifulSoup

"""
#-----------------------use URL-----------------------------------
base_url = "http://www.runoob.com/"
page = requests.get(base_url)
#page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)

#-----------------------use URL end-----------------------------------
"""


file ='./runoob_cainiao.html'
tree = html.parse(file)

#This will create a list of buyers:

lists = root.xpath('/html/body/div[4]/div/div[2]/div/a/strong/text()')

#print the lists
for list in lists:
    print('list: '+ '\n' ,list)

2 Beautifulsoup

REF https://blog.csdn.net/fwj_ntu/article/details/78843872

from lxml import html,etree
import requests

from bs4 import BeautifulSoup

"""
#-----------------------use URL-----------------------------------
base_url = "http://www.runoob.com/"
page = requests.get(base_url)
#page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)

#-----------------------use URL end-----------------------------------
"""


file ='./runoob_cainiao.html'
#tree = html.parse(file)
#使用open函数打开文件
htmlfile = open(file, 'r', encoding='utf-8')

#读取html的句柄内容
htmlhandle = htmlfile.read()

#使用Beautifulsoup解析
soup = BeautifulSoup(htmlhandle, features='lxml')


print(soup.find('h1').get_text(), 'url: ',file)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值