Python 为什么检索到的数据显示为空白,而不是输出正确的数字?

Python 为什么检索到的数据显示为空白,而不是输出正确的数字?,python,web-scraping,python-requests,extract,re,Python,Web Scraping,Python Requests,Extract,Re,我似乎看不出少了什么。为什么回应没有打印ASIN import requests import re urls = [ 'https://www.amazon.com/s?k=xbox+game&ref=nb_sb_noss_2', 'https://www.amazon.com/s?k=ps4+game&ref=nb_sb_noss_2' ] for url in urls: content = requests.get(url).content

我似乎看不出少了什么。为什么回应没有打印ASIN

import requests
import re

urls = [
    'https://www.amazon.com/s?k=xbox+game&ref=nb_sb_noss_2',
    'https://www.amazon.com/s?k=ps4+game&ref=nb_sb_noss_2'
]

for url in urls:
    content = requests.get(url).content
    decoded_content = content.decode()

    asins = set(re.findall(r'/[^/]+/dp/([^"]+)', decoded_content))
    print(asins)
回溯

set()
set()
[Finished in 0.735s]

正则表达式不应用于解析HTML。对于这样的问题,每个人都不推荐使用正则表达式来处理HTML。很难编写足够复杂的正则表达式,以便从每个
获取数据asin值。这将使这项任务更容易。但如果必须使用regex,则此代码将返回body标记内的所有内容:

re.findall(r'<body.*?>(.+?)</body>', decoded_content, flags=re.DOTALL)
如果您正在从文件中读取html,则:

from bs4 import BeautifulSoup
import requests

def getAsins(location_to_file):
    file = open(location_to_file)
    soup = BeautifulSoup(file, 'html.parser')
    asins = {}
    for asin in soup.find_all('div'):
        if asin.get('data-asin'):
            asins[asin.get('data-uuid')] = asin.get('data-asin')
    return asins

关于使用正则表达式从HTML中提取信息,有一个重要的问题。此外,您可能会遇到有关自动访问Amazon数据的错误。在处理内容之前,您应该检查响应状态代码。我知道您现在在说什么。通过标题,我可以看到您所指的消息。有没有办法使用BeautifulSoup检索asin?我添加了一个示例,返回一个字典,其中
'data-uuid'
作为键,
'data-asin'
作为值。您也可以使用
myList.append(asin.get('data-asin'))
创建asin列表。它们的键和值的用途是什么?键需要在值之前还是顺序无关紧要?编辑:我得到的响应为空括号:{}字典将条目存储为键值对。使用键访问值的方式与按位置访问列表值的方式相同<代码>指令['key'],列表[0]。我用这段代码得到空括号的唯一方法是如果我的标题不正确
print(soup.prettify())
检查您是否获得了真实的网页。
file=open('file.html')
然后
soup=BeautifulSoup(file,'html.parser')
from bs4 import BeautifulSoup
import requests

def getAsins(location_to_file):
    file = open(location_to_file)
    soup = BeautifulSoup(file, 'html.parser')
    asins = {}
    for asin in soup.find_all('div'):
        if asin.get('data-asin'):
            asins[asin.get('data-uuid')] = asin.get('data-asin')
    return asins