Проблема с очисткой данных с сайта с помощью Python

Я пытаюсь очистить текст из строки с помощью Python. Мне удалось получить атрибут класса из той же строки, но не из текста, пробовал .text и .get_text(), и ни один из них не работает.

Что мне не хватает?

Вот мой скрипт Python для получения текста из строки:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import datetime
import csv
    
    class toy(object):
    
        browser = webdriver.Chrome(ChromeDriverManager().install())
    
        browser.get('https://continuumgames.com/product/16-tracer-racer-set/')
        time.sleep(2)
    
        try:
            test = browser.find_element_by_xpath('//*[@id="tab-additional_information"]/table/tbody/tr[3]/td').get_attribute('class')
    
        except:
            test = 'NA'
    
        try:
            upcode = browser.find_element_by_xpath('//*[@id="tab-additional_information"]/table/tbody/tr[3]/td').text
    
        except:
            upcode = 'NA'
    
    
        print(test)
        print(upcode)
    
    
        browser.close()

Вот HTML страницы:

<div class="woocommerce-Tabs-panel woocommerce-Tabs-panel--additional_information panel entry-content wc-tab" id="tab-additional_information" role="tabpanel" aria-labelledby="tab-title-additional_information" style="display: none;">
 
    <table class="woocommerce-product-attributes shop_attributes">
        <tbody>
            <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--weight">
               <th class="woocommerce-product-attributes-item__label">Weight</th>
               <td class="woocommerce-product-attributes-item__value">2.5 oz</td>
            </tr>
            <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--dimensions">
               <th class="woocommerce-product-attributes-item__label">Dimensions</th>
               <td class="woocommerce-product-attributes-item__value">24 × 4 × 2 in</td>
            </tr>
            <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--attribute_product_upc">
               <th class="woocommerce-product-attributes-item__label">UPC</th>
               <td class="woocommerce-product-attributes-item__value">605444972168</td>
            </tr>
        </tbody>
     </table>
</div>

Вот мой пробег:

C:\Users\Carre\scrape>python test.py

[WDM] - Current google-chrome version is 83.0.4103
[WDM] - Get LATEST driver version for 83.0.4103
[WDM] - Driver [C:\Users\Carre\.wdm\drivers\chromedriver\win32\83.0.4103.39\chromedriver.exe] found in cache

DevTools listening on ws://127.0.0.1:56807/devtools/browser/03318f43-1d26-44c7-8d90-65233969f03b
woocommerce-product-attributes-item__value

person jinami    schedule 12.07.2020    source источник
comment
пинговать ссылку на сайт   -  person bigbounty    schedule 12.07.2020


Ответы (2)


Ваш селектор, вероятно, выключен. Попробуйте использовать XPath. Щелкните правой кнопкой мыши тег и выберите «Копировать Xpath». Затем замените свой код этим.

upcode = browser.find_element_by_xpath('paste XPath here').text
person bigshirtjp    schedule 12.07.2020
comment
Я пробовал с Xpath, и мне удалось увидеть текст с помощью помощника Xpath, но при запуске скрипта python он не печатает текст. - person jinami; 12.07.2020
comment
не видя кода, где вы печатаете xpath, я не могу вам помочь. опубликуйте достаточно вашего кода, чтобы я мог воспроизвести - person bigshirtjp; 12.07.2020

У меня есть ваше решение, это мой обычный обходной путь при работе с несоответствиями в селене: переключитесь на beautifulsoup4

from selenium import webdriver
import bs4
from webdriver_manager.chrome import ChromeDriverManager
import time
import datetime
import csv



class toy(object):

    browser = webdriver.Chrome(ChromeDriverManager().install())

    browser.get('https://continuumgames.com/product/16-tracer-racer-set/')
    time.sleep(2)

    try:
        test = browser.find_element_by_xpath('//*[@id="tab-additional_information"]/table/tbody/tr[3]/td').get_attribute('class')

    except:
        test = 'NA'

    try:
        upcode = browser.find_element_by_xpath('//*[@id="tab-additional_information"]/table/tbody/tr[3]/td')
        upcode = bs4.BeautifulSoup(upcode.get_attribute('outerHTML'))
        upcode = upcode.text

    except:
        upcode = 'NA'


    print(test)
    print(upcode)


    browser.close()
person eliottness    schedule 12.07.2020
comment
Теперь он работает с bs4, большое спасибо за ваш совет. Я перехожу на bs4, так же, как вы сказали о несоответствиях в селене, было не весело бороться с кодом, даже если в логике все было в порядке. - person jinami; 13.07.2020