【问题标题】:how to fetch data from javascript loaded site using beautifulsoup如何使用beautifulsoup从加载了javascript的站点中获取数据
【发布时间】:2020-07-28 17:20:12
【问题描述】:

我正在尝试从该网站获取一些数据

https://www.walmart.com/store/2141-philadelphia-pa/search?query=ice%20cream

我一直在使用这种方法来获取 javascript 加载的网站

def getLocalStoreProducts():

    session = requests.Session()
    localStoreUrl = 'https://www.walmart.com/store/2141-philadelphia-pa/search?query='
    searchWord = "ice cream"
    searchWord1 = checkForSpace(searchWord)
    wordUrl = localStoreUrl+searchWord1
    print(wordUrl)

    # try:
    categorySoup = BeautifulSoup(session.get(wordUrl).text, 'html.parser')
    categorytagId = find_tag(categorySoup)
    print("this is the tag id ", categorytagId)
    categoryscript = categorySoup.find("script", {"id":categorytagId})
    categorydata = json.loads(categoryscript.get_text(strip=True))


    filename20 = "se.json"
    with open(filename20, "w") as f20:
        json.dump(categorydata, f20)

    print("saved to file")



getLocalStoreProducts()

这是我的查找标签

def find_tag(soup):
    script = soup.find('script', {'type': 'application/json', 'id':re.compile(r'^((?!tb-djs).)*$')})
    return script['id']

但我不断收到此错误

TypeError: 'NoneType' 对象不可下标

我如何从这个 url 获取数据

https://www.walmart.com/store/2141-philadelphia-pa/search?query=ice%20cream

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    要从 Ajax URL 加载 json 数据,您可以使用以下脚本:

    import re
    import json
    import requests
    
    
    url = 'https://www.walmart.com/store/2141-philadelphia-pa/search?query=ice%20cream'
    api_url = 'https://www.walmart.com/store/electrode/api/search'
    
    params = {
        'query': 'ice cream',
        'cat_id': 0,
        'ps': 24,
        'offset': 0,
        'prg': 'desktop',
        'stores': re.search(r'store/(\d+)', url).group(1)
    }
    
    data = requests.get(api_url, params=params).json()
    # print data to screen:
    print(json.dumps(data, indent=4))
    

    打印:

    {
        "items": [
            {
                "productId": "6W2PTANOXU63",
                "usItemId": "336104115",
                "productType": "REGULAR",
                "title": "<mark>Ice</mark> <mark>Cream</mark> Slime - Rainbow Sherbet, 6 fl oz",
                "description": "@generated",
                "imageUrl": "http://i5.walmartimages.com/asr/e107a36f-9cde-4119-978c-99509d8e47d7_1.5e79836a5963dbc2ab8c3e67385ed661.png?odnHeight=180&odnWidth=180&odnBg=ffffff",
                "productPageUrl": "/ip/Ice-Cream-Slime-Rainbow-Sherbet-6-fl-oz/336104115",
                "department": "Food",
                "customerRating": 3,
                "numReviews": 2,
                "sellerId": "F55CDC31AB754BB68FE0B39041159D63",
                "sellerName": "Walmart.com",
                "enableAddToCart": false,
                "canAddToCart": false,
                "showPriceAsAvailable": true,
                "highlightedTitleTerms": [
                    "Cream",
                    "Ice"
                ],
                "seeAllName": "All Ice Cream",
                "seeAllLink": "query=ice%20cream&cat_id=976759_976791_1001420_1001423_4833164&stores=2141&ps=24",
                "itemClassId": "1",
                "primaryOffer": {
                    "offerId": "896BDD106566491C885E6D872F57DA8A",
                    "offerPrice": 0.5,
                    "currencyCode": "USD"
                },
                "fulfillment": {
                    "isSOI": true,
                    "isPUT": false
                },
                "inventory": {
                    "status": "In Stock",
                    "displayFlags": [
                        "IN_STORE_ONLY"
                    ],
                    "available": true
                },
                "quantity": 17,
                "brand": [
                    "Slime Factory"
                ],
                "wmtgPricePerUnitQuantity": "1.0000",
                "standardUpc": [
                    "00885777909776"
                ],
                "isHeartable": true,
                "marketPlaceItem": false,
                "virtualPack": false,
                "preOrderAvailable": false,
                "premiumBrand": false,
                "wfsEnabled": false,
                "blitzItem": false,
                "shippingPassEligible": false,
                "pickupDiscountEligible": false,
                "is_limited_qty": false
            },
            {
                "productId": "3Q1N47LYQKVD",
                "usItemId": "24008061",
                "productType": "REGULAR",
                "title": "Great Value <mark>Ice</mark> <mark>Cream</mark> Variety Pack, 32 Count",
                "description": "<li>12 <mark>Ice</mark> <mark>Cream</mark> Sandwich
    
    
    ...and so on.
    

    【讨论】:

    • 我正在尝试解决这个问题,请您解释一下参数以及您是如何计算出来的。
    • @learner101 我打开了 Firefox 开发者工具 -> 网络选项卡,看到页面发出请求的位置(Chrome 有类似的东西)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2021-12-27
    • 2019-11-16
    • 1970-01-01
    • 2021-10-31
    • 2020-03-03
    相关资源
    最近更新 更多