веб-соскоб продукт и хранить информацию из Target - PullRequest
0 голосов
/ 22 февраля 2019

Я новичок в веб-поиске и собираю данные о продукте с сайта Target.

Подсвеченные части изображения

enter image description here

Мне удалось получить название продукта и цену, но остальная информация не может быть найдена с помощью BeautifulSoup.Например, при проверке почтового индекса он показывает почтовый индекс с тегом data-test, но при поиске тега он не может быть найден.Кто-нибудь испытывал это раньше или знает способ получить эту информацию?

Использование Python 3 и BeautifulSoup.

Не уверен, что лучший способ сформулировать этот вопрос, поэтому дайте мне знать, если вам нужно больше информации или мне нужно перефразировать.

<a href="#" class="h-text-underline Link-sc-1khjl8b-0 jvxzGg" data-test="storeFinderZipToggle">35401</a>
import requests
from bs4 import BeautifulSoup

f = open("demofile.txt", "w")

Page_Source = "https://www.target.com/p/nintendo-switch-with-neon-blue-and-neon-red-joy-con/-/A-52189185"

page = requests.get(Page_Source)

soup = BeautifulSoup(page.content, 'html.parser')

#write all the html code to a file to compare source files
f.write(str(soup))

#should contain city location but Secondary header can't be found
#location = soup.find("div", {'class', 'HeaderSecondary'})


#inside the secondary header should contain the store name but is not found
#store_location = location.find('div', {'data-test': 'storeId-store-name'})
#store_location = location.find('button', {'id': 'storeId-utility-NavBtn'})



#contains the rest of the information interested in
main_container = soup.find(id="mainContainer")
#complete_product_name = soup('span',attrs={'data-test':'product-title'})[0].text
product_price = soup.find("span", {'data-test': 'product-price'})
product_title = soup.find("span", {'data-test': 'product-title'})

flexible_fulfillment = main_container.find('div', {'data-test': 'flexible_fulfillment'})

#test = product_zip.find_all('a')
#example = soup.find_all("div", {'data-test': 'storePickUpType'})

example = soup.findAll('div', attrs={'data-test':'maxOrderQuantityTxt'})
print(product_title)
print(product_price)

print(flexible_fulfillment)


f.close()

1 Ответ

0 голосов
/ 26 февраля 2019

Обновление: полезный совет по использованию Selenium.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException


#launch url
url = "https://www.target.com/p/nintendo-switch-with-neon-blue-and-neon-red-joy-con/-/A-52189185"

# create a new Firefox session
driver = webdriver.Safari()
driver.implicitly_wait(15)
driver.get(url)

try:
    store_name_element = driver.find_element(By.XPATH, '//*[@id="storeId-utilityNavBtn"]/div[2]')
    print(store_name_element.get_attribute('innerText'))
except Exception:
    print "There's no store name available"

try:
    item_name_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[1]/div[1]/h1/span')
    print(item_name_element.get_attribute('innerText'))
except Exception:
    print "There's no item name available"

try:
    price_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[1]/span')
    print(price_element.get_attribute('innerText'))
except Exception:
    print "There's no pricce available"

try:
    zip_code_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[6]/div/div[1]/div[1]/div/div[1]/a')
    print(zip_code_element.get_attribute('innerText'))
except Exception:
    print "There's no zip code available"

try:
    order_by_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[6]/div/div[1]/div[2]/p')
    print(order_by_element.get_attribute('innerText'))
except Exception:
    print "There's no order by time available"

try:
    arrival_date_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[6]/div/div[1]/div[2]/div/div/span')
    print(arrival_date_element.get_attribute('innerText'))
except Exception:
    print "There's no arrival date available"

try:
    shipping_cost_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[6]/div/div[2]/div/div[1]/div[1]/div[1]/div[1]')
    print(shipping_cost_element.get_attribute('innerText'))
except Exception:
    print "There's no shipping cost available"

try:
    current_inventory_element = driver.find_element(By.XPATH, '//*[@id="mainContainer"]/div/div/div[1]/div[2]/div/div[6]/div/div[2]/div/div[1]/div[1]/div[1]/div[2]')
    print(current_inventory_element.get_attribute('innerText'))
except Exception:
    print "There's no current inventory available"

driver.quit()

Одна вещь, которую я заметил в этом коде, это то, что он не согласуется с его результатами.Иногда я получаю ошибки, говоря, что элемент не найден, а в других случаях он найдет элемент.Кто-нибудь знает, почему это может быть?потому что я часто обращаюсь к сайту?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...