【问题标题】:How to extract data within a cdata tag using python?如何使用python提取cdata标签中的数据?
【发布时间】:2015-07-24 05:33:33
【问题描述】:

我使用漂亮的汤从 html 页面获取 CDATA,但我必须从中提取内容并将其放入 csv 文件中。

这是我的代码:

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import csv
f = open('try.html')
ff = csv.writer(open("profiletry.csv", "w"))
ff.writerow(["cdata"]) 
soup = BeautifulSoup(''.join(f.readlines()))
cdata = soup.find(text=re.compile("CDATA"))
print(cdata)
ff.writerow([cdata])
newfile = open('cdatatxt.txt','w')
newfile.write(cdata)
soup = BeautifulSoup(''.join(f.readlines()))
c_data = soup.find(text=re.compile("string"))
print(c_data)

如果我编译这个 cdata 被打印,但我想以键值对的形式获取其中的数据,以便我可以将它存储在 csv 文件中。

【问题讨论】:

标签: python html xml beautifulsoup cdata


【解决方案1】:

这可能会对你有所帮助。

 import re
 from bs4 import BeautifulSoup

 soup = BeautifulSoup(content)
 for x in soup.find_all('item'):
 print re.sub('[\[CDATA\]]', '', x.string)

【讨论】:

  • 我应该根据我的代码用 cdata 替换 item 吗?
  • @shahnazshariff 你得到解决方案了吗?
  • import re from bs4 import BeautifulSoup f = open('try2.html') soup = BeautifulSoup(''.join(f.readlines())) cdata = soup.find(text=re. compile("CDATA")) print(cdata) match = re.search(r'txt: \"\d\"',cdata) if match: print(match.group()) else: print('没找到') --> 使用搜索功能而不是 sub
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 2021-12-28
相关资源
最近更新 更多