【问题标题】:Web-scraping with beautifulsoup returns empty list使用 beautifulsoup 进行网页抓取返回空列表
【发布时间】:2021-11-15 06:19:12
【问题描述】:

您能帮我知道产品的名称吗?

你可以看到图片上的路径

这里的产品名称是Samsung Galaxy....和其他代码

我尝试了什么

import pandas as pd
import requests # Import the library for sending requests to the server
from bs4 import BeautifulSoup # Import the library for webpage parsing

URL='https://www.amazon.com/s?k=samsung+tablet&crid=3VMSMTMZYOP78&sprefix=samsung+%2Caps%2C273&ref=nb_sb_ss_ts-doa-p_2_8'
req = requests.get(URL) # GET-request

soup = BeautifulSoup(req.text, 'lxml')
soup.find_all('span', attrs={'class_':'a-size-medium a-color-base a-text-normal'})

问题

我得到一个空列表。 我不明白为什么会这样。

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

检查这些它将起作用:

from bs4 import BeautifulSoup
import requests
import pandas as pd
products=[]
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
    "Accept-Encoding": "gzip, deflate",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "DNT": "1",
    "Connection": "close",
    "Upgrade-Insecure-Requests": "1",
}
for page in range(1, 5):
    cookies = {'session': '17ab96bd8ffbe8ca58a78657a918558'}
    r = requests.get(
        "https://www.amazon.com/s?k=samsung+tablet&crid=3VMSMTMZYOP78&sprefix=samsung+%2Caps%2C273&ref=nb_sb_ss_ts-doa-p_2_8={page}".format(
            page=page
        ),
        headers=headers,
        cookies =cookies
    )
    soup = BeautifulSoup(r.content, "lxml")
    for d in soup.select(".s-result-item[data-component-type='s-search-result']"):
        name=d.find('h2')
        if name is not None:
            products.append(name.text)
        else:
            products.append("-")

df = pd.DataFrame({'Product Name':products})
print(df)

0

输出:

                                        Product Name
0   SAMSUNG Galaxy Tab S7 FE 2021 Android Tablet 1...
1   Samsung Galaxy Tab A7 10.4 Wi-Fi 32GB Silver (...
2   Samsung Galaxy Tab A7 10.4 Wi-Fi 32GB Silver (...
3   Samsung Tab A7 Lite 8.7" Gray 32GB (SM-T220NZA...
4   SAMSUNG Galaxy Tab A 8.0-inch Android Tablet 6...
..                                                ...
83  2020 Samsung Galaxy Tab A7 10.4�� (2000x1200) ...
84  Samsung Galaxy Tab S6 Lite 10.4�� Touchscreen ...
85  Samsung Galaxy Tab S6 Lite 10.4", 64GB Wi-Fi T...
86  SAMSUNG Galaxy Tab S7 11-inch Android Tablet 1...
87  SAMSUNG Galaxy S20 FE 5G Factory Unlocked Andr...

【讨论】:

  • 选择class_=h2标签而不是class_=a-size-medium a-color-base a-text-normal
  • try这些代码??
【解决方案2】:

您可能应该调整您的 URL 以进行抓取。

使用 curl 测试

当我使用此 URL 运行 curl 请求时,响应的 HTML 不包含预期的 <span class="a-size-medium a-color-base a-text-normal">

curl 'https://www.amazon.com/s?k=samsung+tablet&crid=3VMSMTMZYOP78&sprefix=samsung+%2Caps%2C273&ref=nb_sb_ss_ts-doa-p_2_8' | grep "<span class="

但只有以下跨度:

                                    <span class="a-button a-button-primary a-span12">
                                        <span class="a-button-inner">
            <span class="a-letter-space"></span>
            <span class="a-letter-space"></span>
            <span class="a-letter-space"></span>
            <span class="a-letter-space"></span>

试汤

您也可以将soup 测试为HedgeHog commented

import requests # Import the library for sending requests to the server
from bs4 import BeautifulSoup # Import the library for webpage parsing

url ='https://www.amazon.com/s?k=samsung+tablet&crid=3VMSMTMZYOP78&sprefix=samsung+%2Caps%2C273&ref=nb_sb_ss_ts-doa-p_2_8'
response = requests.get(url) # GET-request

soup = BeautifulSoup(response.text, 'html')  # adjusted from lxml to html
print(soup) # contains span elements but not expected

elements = soup.find_all('span', attrs={'class_':'a-size-medium a-color-base a-text-normal'})
print(elements) # empty list, the expected spans were not found

您会发现一种机器人预防措施,可能使用验证码来验证人类是否正在使用浏览器:

<h4>Enter the characters you see below</h4>
<p class="a-last">Sorry, we just need to make sure you're not a robot. For best results, please make sure your browser is accepting cookies.</p>

趣事: 您可以将生成的 HTML 复制并粘贴或写入文件并在浏览器中打开。它显示了亚马逊的看门狗:

另见All The Dogs You Can Meet If You're Trying To Get On Amazon But It's Broken

解决方法:传递所需的请求标头

进一步的研究建议在请求中添加 2 个标头(您的浏览器也会自动添加):

  • 有效的User-Agent(可以模拟特定的浏览器和操作系统/平台)
  • Accept-Language(大多数电子商务页面都需要将内容本地化)

requests 中,您可以将它们添加为字典,例如:

HEADERS = ({
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
    'Accept-Language': 'en-US, en;q=0.5'
})
  
response = requests.get(URL, headers=HEADERS)

见:

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2018-08-02
    相关资源
    最近更新 更多