因此,我一直在嘗試使用 scrape 來(lái)學(xué)習(xí)一些知識(shí),在那里我設(shè)法抓取了一個(gè)返回大量不同 var 值的站點(diǎn),例如:var FancyboxI18nClose = 'Close';var FancyboxI18nNext = 'Next';var FancyboxI18nPrev = 'Previous';var PS_CATALOG_MODE = false;var added_to_wishlist = '.';var ajax_allowed = true;var ajaxsearch = true;var attribute_anchor_separator = '-';var attributesCombinations = [{"id_attribute":"100","id_attribute_group":"1","attribute":"38_5"},{"id_attribute":"101","id_attribute_group":"1","attribute":"39"},{"id_attribute":"103","id_attribute_group":"1","attribute":"40"},{"id_attribute":"104","id_attribute_group":"1","attribute":"40_5"},{"id_attribute":"105","id_attribute_group":"1","attribute":"41"},{"id_attribute":"107","id_attribute_group":"1","attribute":"42"},{"id_attribute":"108","id_attribute_group":"1","attribute":"42_5"},{"id_attribute":"109","id_attribute_group":"1","attribute":"43"},{"id_attribute":"111","id_attribute_group":"1","attribute":"44"},{"id_attribute":"112","id_attribute_group":"1","attribute":"44_5"},{"id_attribute":"132","id_attribute_group":"1","attribute":"45"},{"id_attribute":"113","id_attribute_group":"1","attribute":"46"}];當(dāng)然還有更多,它們都只包含在 var 中。但是,我想要做的是只能抓取其中一個(gè)值 - var attributesCombinations意味著我基本上只想打印出該值,然后我可以使用 json.loads 在那里我可以更輕松地抓取 json。我試圖做的是以下內(nèi)容:try: product_li_tags = bs4.find_all(text=re.compile('attributesCombinations'))except Exception: product_li_tags = []但這給了所有“var”開始到 where 的結(jié)果attributesCombinations。['var CUSTOMIZE_TEXTFIELD = 1;\nvar FancyboxI18nClose = \'Close\';\nvar FancyboxI18nNext = \'Next\';\nvar FancyboxI18nPrev = \'Previous\';\nvar PS_CATALOG_MODE = false;\nvar added_to_wishlist = \'The product was successfully added to your wishlist.\';\nvar ajax_allowed = true;\nvar ajaxsearch = true;\nvar allowBuyWhenOutOfStock = false;\nvar attribute_anchor_separator = \'-\';\nvar attributesCombinations = [{"id_attribute":"100","id_attribute_group":"1","att...........我如何使它只打印出var attributesCombinations?
2 回答

紫衣仙女
TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
提取(僅)從attributesCombinations
到語(yǔ)句末尾的部分的正則表達(dá)式是
var attributesCombinations = (\[.*?\])
在 Python 中,您可以輕松地創(chuàng)建正則表達(dá)式
re.compile(r'var attributesCombinations = (\[.*?\])');

慕田峪9158850
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
不要re.compile在bs4中使用,直接運(yùn)行。
match = re.compile('var\s*attributesCombinations\s*=\s*(\[.*?\])').findall(htmlString)
attributesCombinations = json.loads(match[0])
print(attributesCombinations)
添加回答
舉報(bào)
0/150
提交
取消