Схватить единицы для материала - PullRequest
0 голосов
/ 21 мая 2018

Я использую Selenium для получения информации о материалах с веб-сайта.Я не могу понять, как получить какой-то отдельный текст в тегах div, не захватывая другую информацию div.Что такое правильный XPATH, чтобы получить количество единиц из следующего HTML-кода?

<div class="pricingReg xh-highlight" itemprop="offers" itemscope="" itemtype="http://schema.org/Offer" xpath="1">
    <span id="ajaxPrice" class="pReg" itemprop="price" content="29.98">
        <span class="price__currency">$</span><span class="price__dollars" style="">29</span>
        <span class="price__cents">98</span>
    </span>
        /each
    <link itemprop="availability" href="http://schema.org/InStock">
    <meta itemprop="priceCurrency" content="USD">
</div>

Пока я пробовал:

try:
  element = "//div[@class='pricingReg']"
  el = driver.find_element(By.XPATH, element)
  el_text = el.get_attribute("innerText")
  print(el_text)
  purchase_unit_label = re.search('^[a-zA-Z]*$', el_text)
  print('Purchase Unit Label =' + purchase_unit_label)
except NoSuchElementException:
  print('Purchase Unit Label NoSuchElementException')

Это дает мне следующий вывод в консоли:

Name: 3/8 in. x 100 ft. Diamond-Braid Poly Rope
Description: 3/8 in. x 100 ft. Diamond Braid Poly Rope is designed for maximum strength and durability. It's made with a polypropylene jacket covering a mixed synthetic core. Common uses include: securing equipment, making a shelter, using as a rescue line, lifting objects with a pulley and tying down loads and using while camping or boating. Do not use for overhead lifting.
Image: https://images.homedepot-static.com/productImages/9b89db7a-5ecd-41a0-8ebb-1924ce3176aa/svn/multi-everbilt-rope-14156-64_1000.jpg
cost_per_purchase_unit = 998.0

                    $998
Traceback (most recent call last):
  File "C:/Users/my_user/PycharmProjects/scraper/hd_scraper_materials.py", line 200, in <module>
print('Purchase Unit Label =' + purchase_unit_label)
TypeError: must be str, not NoneType

Вы можете видеть, как я получаю% 998 в приведенном выше примере, когда я действительно надеюсь получить «каждый».

1 Ответ

0 голосов
/ 22 мая 2018

хорошо, у этих div'ов есть атрибуты и значения, поэтому ... с помощью css (при условии, что это связано с тегом css-selector в вопросе):

селекторы для ... price__currency:

.prince__currency

цена__долларов:

.price__dollars

цена__центов:

.price__cents

атрибут itemprop:

link[itemprop] or meta[itemprop]

я никогда не работал с селеном, но могу написать jqueryдля вас, чтобы экстраполировать:

$("input[value='Hot Fuzz']" ).next().text( "Hot Fuzz" );

alert ($("input[name='news']").attr('customAttribute'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>
    <input type="radio" name="newsletter" value="Hot Fuzz">
    <span>name?</span>
  </label>
</div>
<div>
  <label>
    <input type="radio" name="newsletter" value="Cold Fusion">
    <span>value?</span>
  </label>
</div>
<div>
  <label>
    <input type="radio" name="newsletter" value="Evil Plans">
    <span>value?</span>
  </label>
  <label>
     <input name="news" type="text" customAttribute="quantity:98" />
  </label>
</div>

Надеюсь, это поможет вам

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