【问题标题】:What is the best way to store HTML elements with BeautifulSoup for later use?用 BeautifulSoup 存储 HTML 元素以供以后使用的最佳方法是什么?
【发布时间】:2021-09-08 11:58:41
【问题描述】:

我的目标是使用 BeautifulSoup,提取某些 HTML 元素(在这种情况下包含字母),存储它们,然后使用 javascript 在原始网站上识别它们(例如,使用 document.getElementsbyClassName...)

我正在使用以下 Python 代码提取 HTML 元素:

from bs4 import BeautifulSoup
import re 

def parse_html(html): 
    soup = BeautifulSoup(r.text, 'html.parser')
    
    text_only = []

    for elem in soup(text= re.compile('[A-Za-z]+')) :
            text_only.append(elem)
            
    return text_only


然后我将其存储在数据库中。我的用例是我想稍后使用这些来识别原始网站上的特定元素。但我不确定我该怎么做?我使用this代码生成Xpath,存储然后用这个JS代码在原网站上使用:

let parse = document.evaluate("/html/body/div[1]/div[2]/div[4]/ul/li[3]/a", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

但是,这返回未定义。我该如何解决?

【问题讨论】:

    标签: javascript python html xpath beautifulsoup


    【解决方案1】:

    您可以将 HTML 内容保存为 json 或 txt,前提是 HTML 内容应为字符串。我保存为txt格式。试试这个,看看你是否达到了你的期望。

    URL = 'some_url'
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    
    #open and write the file (html should be stored in string format)
    file_open = open("html_file.txt", "w")
    file_open.write(str(soup))
    file_open.close()
    
    #open and read file
    file_open = open("html_file.txt", "r")
    file_read = file_open.read()
    file_open.close()
    
    #reuse saved HTML code
    reuse_html = BeautifulSoup(file_read, 'html.parser')
    print(reuse_html)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2011-04-04
      • 2010-11-12
      • 2021-05-27
      相关资源
      最近更新 更多