在搜索栏中输入查询并抓取结果

时间:2019-09-21 12:22:20

标签: python web-scraping beautifulsoup selenium-chromedriver

我有一个包含不同书籍的ISBN号的数据库。我使用Python和Beautifulsoup收集了它们。接下来,我想在书籍中添加类别。书籍类别有一个标准。根据标准,名为https://www.bol.com/nl/的网站拥有所有书籍和类别。

起始网址:https://www.bol.com/nl/

ISBN:9780062457738

搜索后的网址:https://www.bol.com/nl/p/the-subtle-art-of-not-giving-a-f-ck/9200000053655943/

HTML类类别:<li class="breadcrumbs__item"

有人知道如何(1)在搜索栏中输入ISBN值,(2)然后提交搜索查询并使用该页面进行抓取?

步骤(3),我可以抓取所有类别。但是我不知道如何执行前两个步骤。

我到目前为止在步骤(2)中拥有的代码

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

webpage = "https://www.bol.com/nl/" # edit me
searchterm = "9780062457738" # edit me

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(webpage)

sbox = driver.find_element_by_class_name("appliedSearchContextId")
sbox.send_keys(searchterm)

submit = driver.find_element_by_class_name("wsp-search__btn  tst_headerSearchButton")
submit.click()

我到目前为止在步骤(3)中拥有的代码

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.bol.com/nl/p/the-subtle-art-of-not-giving-a-f-ck/9200000053655943/')

soup = BeautifulSoup(data.text, 'html.parser')

categoryBar = soup.find('ul',{'class':'breadcrumbs breadcrumbs--show-last-item-small'})

for category in categoryBar.find_all('span',{'class':'breadcrumbs__link-label'}):
    print(category.text)

2 个答案:

答案 0 :(得分:0)

您可以使用selenium来找到输入框并在您的ISBN上循环,分别输入:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
d = webdriver.Chrome('/path/to/chromedriver')
books = ['9780062457738']
for book in books:
  d.get('https://www.bol.com/nl/')
  e = d.find_element_by_id('searchfor')
  e.send_keys(book)
  e.send_keys(Keys.ENTER)
  #scrape page here 

现在,对于books中的每本书ISBN,解决方案都会将值输入搜索框并加载所需的页面。

答案 1 :(得分:0)

您可以编写一个返回类别的函数。您可以基于实际搜索来进行搜索,页面只会整理参数,并且可以使用GET。

import requests
from bs4 import BeautifulSoup as bs

def get_category(isbn): 
    r = requests.get(f'https://www.bol.com/nl/rnwy/search.html?Ntt={isbn}&searchContext=books_all') 
    soup = bs(r.content,'lxml')
    category = soup.select_one('#option_block_4 > li:last-child .breadcrumbs__link-label')

    if category is None:
        return 'Not found'
    else:
        return category.text

isbns = ['9780141311357', '9780062457738', '9780141199078']

for isbn in isbns:
    print(get_category(isbn))