Find Python Beautiful Soup Regular Expression

Asked 2 years ago, Updated 2 years ago, 149 views

I'd like to modify the numbers in the QTY column as shown in the picture.

The code in each QTY column is a code that changes only the last digit, such as txtAvailableQTY_0, txtAvailableQTY_1, txtAvailableQTY_2.

So I made a code using a regular expression, but I keep getting errors.

html = driver.page_source
soup = BeautifulSoup(html,'html.parser')
QTY = soup.find(id=re.compile('rpQuickEdit_txtAvailableQTY_[0-9]{1,2}'))


for i in range(5):
    if QTY is True:
        driver.find_element_by_css_selector(QTY).click()
        action = ActionChains( driver )
        action.send_keys( Keys.BACKSPACE ).send_keys('0').perform()

I made the code like this, but which part is the problem?

I'd like to revise the numbers in the QTY column.

I cut it because the cord was too long, but I'm using selenium and web drive.

python if문 beautifulsoup regex

2022-09-22 19:30

2 Answers

The find method is to find only one.

You must use find_all.

Please refer to the sample below.

html = '''
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" version="XHTML+RDFa 1.0" dir="ltr" class="js">
<body>
<div id="aaaa_0">aaaa</div>
<div id="aaaa_1">bbbb</div>
<div id="bbbb_0">bbbb</div>
</body>
</html>
'''

import re
import bs4

bs = bs4.BeautifulSoup(html, 'html.parser')
bs.find_all(id=re.compile('aaaa_[0-9]{1,2}'))

[<div id="aaaa_0">aaaa</div>, <div id="aaaa_1">bbbb</div>]


2022-09-22 19:30

for i in random(5):
    QTY = soup.find(id='rpQuickEdit_txtAvailableQTY_' + str(i)))
    If QTY is not None: # soup.find() returns None if nothing is found


2022-09-22 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.