【问题标题】:Extract Javascript Variables from Scraped HTML Page using PHP (Regex)使用 PHP(正则表达式)从抓取的 HTML 页面中提取 Javascript 变量
【发布时间】:2021-04-14 13:45:16
【问题描述】:

我正在努力从抓取网页的 HTML 转储中提取 Javascript 变量。

目前正在使用这个正则表达式

    $re = '/window\.universal_variable\s*=\s*\{(.*?)\}/ms';

但它只显示了第一组值。我基本上是在尝试获取产品下的所有变量和值(即 id、product_id、sku 等)

    <script type="text/javascript">
window.universal_variable = {
page: {
category: "product" ,
searchTerm: "sony",
environment: "production",
variation: "production",
revision: "1.1"
},
user: {
otb: "",
ATG_FO_IND: "A",\t
ooops_preference: "false",
registered_today: false,
registration_date: "",
registered_in_current_session: false,\tidv_verified: true,
last_order_date: "",
start_date: "",
first_order: false,\treturning: false,
last_transaction_payment_type: "",
unicaSegment: "",
targetedPromos :"",
cva:"0",
cvb:"1", 
cvc:""
}// end of user\t
,\t
product:{
id: "KEN6C",
product_id: "prod1086433641",
sku: "KEN6C",
manufacturer: "",
category: "Televisions",
category_facet: "4740",
department: "Electricals",
subcategory: "electricals_televisions",
currency: "GBP",
unit_price: "",
unit_sale_price: "319.0",
rating: "4.3",
ratingCount: "2048"
}// end of product
}// end of window.universal_variable\t
window.sdgGA = {
environment: "production",
device: "desktop",
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
currency: "GBP",
page: {
PID: "test : PRODUCT",
loggedInState: "not logged in",
category:"product",
customerStatus: "new"
},

</script>

有什么建议吗?

【问题讨论】:

    标签: javascript php regex scrape


    【解决方案1】:

    与其尝试使用非常脆弱的正则表达式,我建议使用诸如this one 之类的转译器。我在您的示例代码上对其进行了测试,效果很好。

    【讨论】:

    • 太棒了。我试试看
    • 在这种情况下,什么是一个好的正则表达式来提取 js 标签之间的所有内容?
    • 我也不推荐正则表达式,因为事先不知道嵌套标签有多少层,而且 HTML 有可能有也可能没有右斜杠的空标签,这使得它复杂的。这个答案是我可能会做的:stackoverflow.com/a/1677190/5774952,但在该问题的其他答案中有一些正则表达式示例。
    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2012-07-07
    • 2011-06-26
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2013-07-25
    相关资源
    最近更新 更多