xpathとlxmlの間の密接な接触

pythonでxpathを使用する方法

Qianmenは非常に多くのxpath構文を言ったので、今それをどのように使うか。ここでの単語は、lxmlライブラリのetreeと切り離せません。ここで、lxmlはC言語で記述されているため、一部の関数メソッドはpycharmでプロンプトが表示されないことに注意してください。
インストールlxmlpip
インストールlxml
はpipを介して直接インストールされます。問題が発生した場合は、pipのインストールについて書いたブログを確認してください。

etreeとxpath(要素)間のリンク

以前のブログの例であるXpathの構文の要約を使用して、この詩のWebサイトを例として引き続き使用します。
ここに写真の説明を挿入
1 Webページのテキストを取得する(html)

from lxml import etree
import requests
headers={
    
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                      ' AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/80.0.3987.149 Safari/537.36'}

url='https://www.elanp.com/shige/'
text_=requests.get(url,headers=headers)
text=text_.content.decode('gb2312')

ここで、Webサイトは「gb2312」エンコーディングを使用していることに注意してください。
2.xpath構文を使用する要素を作成します

html_=etree.HTML(text)
这里得到的是element的类可以使用xpath

ここでは、xpath構文を使用できます。
例:

date_1=html_.xpath('''//div[@class="mypos"]/a[@href="//www.elanp.com"/]text()''']

結果は次のとおりです。
ここに写真の説明を挿入
ここでetree.HTML()を使用することは、xpathをブリッジとして使用することと同等であるだけでなく、さらに重要なことに、不完全なHTMLコードを完成させることができます。
印刷できます。

htmlcode=etree.tostring(html_,encoding='utf-8').decode('utf-8')
#tostring()方法得到的是bytes数据我们需要将其转化为utf-8,
#同时其默认的编码是Unicode格式,所以要先转化为utf-8的格式之后解码。

より完全なコードは次のとおりです。

from lxml import etree
import requests
headers={
    
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                      ' AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/80.0.3987.149 Safari/537.36'}

url='https://www.elanp.com/shige/'
text_=requests.get(url,headers=headers)
text=text_.content.decode('gb2312')

html_=etree.HTML(text)
date_1=html_.xpath('''//div[@class="mypos"]/a[@href="//www.elanp.com/"]/text()''']
#htmlcode=etree.tostring(html_,encoding='utf-8').decode('utf-8')
#print(htmlcode)
print(date_1)

ここで、前のブログのxpathステートメントを実行します。

  1. / html / head / title / text()
  2. // div [position()= 1] / a [@href = "// www.elanp.com/"]/ text()
  3. // div [@ class =“ mypos”] / a [@href = "// www.elanp.com/"] / text()
  4. // div [position()<2] / a [contains(@href、“ w”)] / @ href
  5. (入力の問題により、ここに示されているxpathステートメントの一部には中国語の記号が付いています。標準としてコードを参照してください)
    結果は次のとおりです。
    ここに写真の説明を挿入

コードは次のように表示されます。

from lxml import etree
import requests
headers={
    
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
                      ' AppleWebKit/537.36 (KHTML, like Gecko)'
                      ' Chrome/80.0.3987.149 Safari/537.36'}

url='https://www.elanp.com/shige/'
text_=requests.get(url,headers=headers)
text=text_.content.decode('gb2312')

html_=etree.HTML(text)
date_1=html_.xpath('''//div[@class="mypos"]/a[@href="//www.elanp.com/"]/text()''']
#htmlcode=etree.tostring(html_,encoding='utf-8').decode('utf-8')
#print(htmlcode)
#print(date_1)
def get_date(xpath_grammar):
    try :
        date_1=html_.xpath(xpath_grammar)
        print(date_1)
    except Exception as e:
        print(e)
if __name__=='__main__':
    value1='''/html/head/title/text()'''
    value2='''//div[position()=1]/a[@href="//www.elanp.com/"]/text()'''
    value3='''//div[@class="mypos"]/a[@href="//www.elanp.com/"]/text()'''
    value4='''//div[position()<2]/a[contains(@href,"w")]/@href'''
    get_date(value1)
    get_date(value2)
    get_date(value3)
    get_date(value4)



ローカルからhtmlテキストをインポートします。

この場合、etree.parse(filename)を使用するだけで済みます
が、parseはHTMLのようなhtmlコードを自動的に完了しないため、直接使用するとエラーが報告される場合があることに注意してください。したがって、インタプリタを指定する必要があります。
その__init__ファイルを見ることができます。
ここに写真の説明を挿入
したがって:

  1. インタプリタを作成します; parse = etree.HTMLParser(encoding = 'utf-8')
  2. インタプリタを指定します; html = etree.parse(filename、parse)
  3. xpath操作; html.xpath(ステートメント)
  4. コードは次のように表示されます。
filename='本地文件名html'
parse=etree.HTMLParser(encoding='utf-8')
html=etree.parse(filename,parse)
#html_text=etree.tostring(html,encoding='utf-8').decode('utf-8')

概要

ついに幸せな一日が終わりました!

おすすめ

転載: blog.csdn.net/FUTEROX/article/details/107451547