我想拉static_token
,但我肯定没有走上正轨。我提取了所有javascript的信息,我的下一步,我想是我需要用JSON读取它或将其转换为JSON格式,因为这是我在前一个问题上被告知的。我试图用正则表达式来解决这个问题,也没有运气,正如评论中指出的那样,我不知道自己在做什么。你能否指出我正确的方向来提取static_token
以及我在这些情况下需要实际做些什么的简要描述?
CODE
import requests
import json, re
from bs4 import BeautifulSoup
url =''' '''
response = requests.get(url)
soup1 = BeautifulSoup(response.text,'lxml')
html1 = soup1.find_all('script')[1] #.text
print(html1)
soup2 = BeautifulSoup(b'html1', 'lxml')
var = soup2.get('var static_token')
print(var)
我尝试使用正则表达式 -
static_token = re.findall(('static_token":"([^"]+)'), soup.text)
print(static_token)
来源我试图提取信息
<script type="text/javascript">var CUSTOMIZE_TEXTFIELD = 1;
var FancyboxI18nClose = 'Close';
var FancyboxI18nNext = 'Next';
var FancyboxI18nPrev = 'Previous';
var contentOnly = false;
var roundMode = 2;
var static_token = '850424cb3feab732e072a3d84e378908';
var taxEnabled = 1;
var titleDelivery = '<h3 class="page-subheading">Your delivery address</h3>';
var titleInvoice = '<h3 class="page-subheading">Your billing address</h3>';
var token = '0c7a8347a263972696d6514dcfa24741';
var txtConditionsIsNotNeeded = 'You do not need to accept the Terms of Service for this order.';
var txtDeliveryAddress = 'Delivery address';
var txtErrors = 'Error(s)';
var txtFree = 'Free';
var txtThereis = 'There is';
var txtWithTax = '(tax incl.)';
var txtWithoutTax = '(tax excl.)';
var usingSecureMode = true;
var vat_management = 0;</script>
答案 0 :(得分:1)
您在这个问题中混淆了很多数据类型。这不是解决这个问题的唯一方法(或最强大的方法),但它很简单,可以指向正确的方向。
您似乎能够使用BeautifulSoup读取html并从中提取脚本标记到html1
。
您需要查看文档以了解所使用的数据类型。我还建议在代码中添加这样的语句来帮助。
html1 = soup.find_all('script')
print('html1', type(html1), html1) # the type is bs4.element.ResultSet
此var包含文档中的所有脚本标记。您可以遍历标记,并查找每个标记的文本字段。但它不是JSON格式的类型。
一旦你有一个字符串并且你想要那部分字符串 - 正则表达式应该是你的第一个想法。你不想在原始的html上使用正则表达式 - 这是BS4库和其他人喜欢它的重点。 HTML经常被破坏,混乱,并且不适合简单的正则表达式。使用BeautifulSoup解析html并找到你想要的部分,然后使用正则表达式来解析字符串。
for tag in html1:
print('tag', type(tag), tag) # bs4.element.Tag
print()
print('tag.text', type(tag.text), tag.text) # str
print()
toks = re.findall("var static_token =\s*'(\w+)'", tag.text)
print('toks', type(toks), toks) # list
print()
static_token = toks[0]
print('static_token', type(static_token), static_token) # str
print()