BeautifulSoup中的find_all()方法返回空列表

时间:2020-06-01 19:15:41

标签: python python-3.x web-scraping beautifulsoup

我是编程新手,也是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()

Edit2

仅使用.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>

2 个答案:

答案 0 :(得分:0)

您的代码没有向我们显示您要解析的网址。

请...尝试理解一个简单页面的概念...

Ebay使用JavaScript,很难报废...

我会写下一个简单的...

希望能帮助您理解一些概念...

from bs4 import BeautifulSoup
import requests

page = "https://en.wikipedia.org/wiki/Main_Page"

page_text = requests.get(page).text

soup = BeautifulSoup(page_text, 'lxml')

# print(soup)
links = []
links = soup.find_all("a")

for link in links:
    print(link)

答案 1 :(得分:0)

BeautifulSoup具有针对不同情况的几种不同类型的解析器。在过去,我坚持使用“ html.parser”而不是“ lxml”。有时在“ html.parser”将返回结果的情况下,使用“ lxml”实际上将返回None。

这可能就是为什么您收到错误消息和空结果的原因,我会尝试这样做。当我写出与您相似的作品时,它起作用了。由于大量使用了a标记,您可能会获得一大堆内容来解析,但是如果您从lxml更改为html.parser,它应该可以工作!

Web抓取可能很难掌握,但是一旦完成,这确实很有趣。确实有很棒的视频谈论Youtube上的beautifulsoup。