【发布时间】:2021-03-16 06:48:25
【问题描述】:
我是编程新手,也是 pyhon 新手。
我的目的是建立一个 ebay 网络爬虫。
我正在尝试使用 bs4 find_all() 方法提取链接列表,但无论我尝试什么,它总是返回一个空列表。
def get_index_data(soup):
try:
links = soup.find_all('a', {'class': 's-item__link'})
print(links)
except:
links = []
print(links)
我也是这样写的。
links = soup.find_all('a', class_= 's-item__link')
它还返回一个空列表。完全不知道怎么回事
编辑:
import requests
from bs4 import BeautifulSoup
def get_page(url):
response = requests.get(url)
if not response.ok:
print('server responded: ', response.status_code)
else:
soup = BeautifulSoup(response.text, 'lxml')
return soup
def get_index_data(soup):
links = soup.find_all('a')
print(links)
def main():
url = 'https://www.ebay.de/sch/i.html?_nkw=armbanduhr&_pgn=1 '
get_index_data(get_page(url))
if __name__ == '__main__':
main()
编辑2
仅使用 .find_all('a') 运行代码后出错
Traceback (most recent call last):
File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 29, in <module>
main()
File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 25, in main
get_index_data(get_page(url))
File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 19, in get_index_data
print(links)
File "C:\Users\Aleksandar\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 28776: character maps to <undefined>
【问题讨论】:
-
您能分享您要废弃的页面,以便我们复制问题吗?
-
也许您尝试抓取的页面使用了动态 Javascript,在这种情况下您无法使用 BeautifulSoup 抓取它。但是,如果是这种情况,您可以使用 Selenium。
-
显而易见的答案是该页面上没有任何
<a class="s-item__link">元素。你能告诉我们soup吗? -
我不知道到底是什么问题,但它可能出在你意想不到的地方。如果你扩大搜索范围,只找到带有 soup.find_all('a') 的“a”元素会发生什么你能遍历它们并找到你正在寻找的类吗?
-
好的,谢谢大家
标签: python python-3.x web-scraping beautifulsoup