[英]Converting a string from scraped javascript into a python dictionary
我想在下面的鏈接中爬取產品的產品描述。
我嘗試使用selenium進行爬網,但信息受網站保護,因此我通過selenium獲得的所有信息與requests相同。 所以為了讓腳本運行得更快,我使用requests來抓取它。
下面是代碼:
import requests
from bs4 import BeautifulSoup as BS
res= requests.get("https://www.real.de/product/345246038/")
soup=BS(res.text,'lxml')
code=soup.prettify()
split = code.split("attributes:")
for value in split:
after=value.split(",condition$:b")
for value in after:
if "{default:[{name:" in value:
clean = value.replace(",highlighted:void 0}}","}").replace(": None","")
這是變量clean中的字符串:
我將 clean 轉換為字典:
import yaml
d = yaml.load(clean)
但它的格式不像字典那樣正確:因為並非所有單詞都在雙引號中( "" )
因此,我使用正則表達式僅提取字符串中不在雙引號中的單詞。 這是代碼:
r = re.compile(r'[{,:][a-zA-z]+[:}]', flags=re.I | re.X)
string = r.findall(clean)
ta=[]
for w in string :
m = re.search('[a-zA-z]+', w)
if m:
new = str('"')+m.group(0)+str('"')
ta.append(new)
然而。 我不知道如何將雙引號 ("") 中的單詞再次放入clean變量中。
你能幫助我嗎?
您可以嘗試(?!")
表示不帶引號的匹配字符
if "{default:[{name:" in value:
clean = value.replace(",highlighted:void 0}}","}").replace(": None","")
# add the lines below
clean = re.sub(r'(\{|,)(?!")(\w+?):', r'\1"\2":', clean)
clean = re.sub(r':(?!")(\w+?)(\}|,)', r':"\1"\2', clean)
jsonData = json.loads(clean)
print(json.dumps(jsonData, indent=2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.