【发布时间】:2018-12-18 20:26:24
【问题描述】:
所以我一直在使用 abit 的 bs4 并设法打印出一个文本。现在我设法打印出 var ajaxsearch 哪个 init 来得更多。
我编写了一个代码,它打印出所有包含 javascript 的内容,并打印出 var ajaxsearch 以它开头的位置:
try:
product_li_tags = bs4.find_all('script', {'type': 'text/javascript'})
except Exception:
product_li_tags = []
special_code = ''
for s in product_li_tags:
if s.text.strip().startswith('var ajaxsearch'):
special_code = s.text
break
print(special_code)
我得到以下输出:
var ajaxsearch = false;
var combinationsFromController ={
"224114": {
"attributes_values": {
"4": "5.5"
},
"attributes": [
22
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'22'"
},
"224140": {
"attributes_values": {
"4": "6"
},
"attributes": [
23
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'23'"
},
"224160": {
"attributes_values": {
"4": "6.5"
},
"attributes": [
24
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'24'"
},
"224139": {
"attributes_values": {
"4": "7"
},
"attributes": [
25
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'25'"
},
"224138": {
"attributes_values": {
"4": "7.5"
},
"attributes": [
26
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'26'"
},
"224113": {
"attributes_values": {
"4": "8"
},
"attributes": [
27
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'27'"
},
"224129": {
"attributes_values": {
"4": "8.5"
},
"attributes": [
28
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'28'"
},
"224161": {
"attributes_values": {
"4": "9"
},
"attributes": [
29
],
"unit_impact": 0,
"minimal_quantity": "1",
"date_formatted": "",
"available_date": "",
"id_image": -1,
"list": "'29'"
}
};
var contentOnly = false;
var Blank = 1;
var Format = 2;
意思是当我打印出 s.text 时。我将得到上面代码的输出。小编辑:如果我尝试执行if s.text.strip().startswith('var combinationsFromController'):,它将找不到该值,并且如果我以相反的方式更改它if 'var combinationsFromController' in s.text.strip():,它将打印出与上述相同的输出。
但是我的问题是我只想能够打印出var combinationsFromController 并跳过其余部分,我稍后可以使用 json.loads 将值转换为 json 但在此之前我的问题是,我该如何打印所以我可以设法获得var combinationsFromController 的值?
编辑:可能解决了!
for s in product_li_tags:
if 'var combinationsFromController' in s.text.strip():
for line in s.text.splitlines():
if line.startswith('var combinationsFromController'):
get_full_text = line.strip()
get_config = get_full_text.split(" = ")
cut_text = get_config[1][:-1]
get_json_values = json.loads(cut_text)
【问题讨论】:
-
如果您的目标是在 Python 中解析 JavaScript,您可以考虑使用现有的库来执行此操作。这篇文章中提到了其中的一些:stackoverflow.com/questions/390992/javascript-parser-in-python
标签: python for-loop beautifulsoup