Цикл BeautifulSoup не перебирает другие узлы - PullRequest
0 голосов
/ 08 января 2019

Есть довольно похожие сценарии относительно этого; но я сравнивал с другими. Получение из кластерных узлов и т. Д. Но как-то; Я не уверен, почему мой for loop не выполняет итерацию и захват текста из других элементов, а только из первого элемента узла.

from requests import get
from bs4 import BeautifulSoup

url = 'https://shopee.com.my/'
l = []

headers = {'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)'}

response = get(url, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')


def findDiv():
     try:
        for container in html_soup.find_all('div', {'class': 'section-trending-search-list'}):
            topic = container.select_one(
                'div._1waRmo')
            if topic:
                print(1)
                d = {
                    'Titles': topic.text.replace("\n", "")}
                print(2)
                l.append(d)
        return d
    except:
        d = None

findDiv()
print(l)

the html elements i'm trying to access

Ответы [ 2 ]

0 голосов
/ 08 января 2019
from requests import get
from bs4 import BeautifulSoup

url = 'https://shopee.com.my/'
l = []

headers = {'User-Agent': 'Googlebot/2.1 (+http://www.google.com/bot.html)'}

response = get(url, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')


def findDiv():
     try:
        for container in html_soup.find_all('div', {'class': '_25qBG5'}):
            topic = container.select_one('div._1waRmo')
            if topic:
                d = {'Titles': topic.text.replace("\n", "")}
                l.append(d)
        return d
     except:
        d = None

findDiv()
print(l)

Выход:

[{'Titles': 'school backpack'}, {'Titles': 'oppo case'}, {'Titles': 'baby chair'}, {'Titles': 'car holder'}, {'Titles': 'sling beg'}]

Снова я предлагаю вам использовать селен . Если вы запустите это снова, вы увидите, что вы получите другой набор из 5 словарей в списке. Каждый раз, когда вы делаете запрос, они дают 5 случайных трендовых предметов. Но у них есть кнопка «изменить». Если вы используете селен, вы можете просто щелкнуть по нему и продолжать отбрасывать все трендовые элементы.

0 голосов
/ 08 января 2019

Попробуйте это: toplevel находит корень опций, затем мы находим все div'ы под этим. Я надеюсь, что это то, что вы хотите.

from requests import get
from bs4 import BeautifulSoup

url = 'https://shopee.com.my/'
l = []

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}

response = get(url, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')


def findDiv():
    try:
        toplevel = html_soup.find('._25qBG5')
        for container in toplevel.find_all('div'):
            topic = container.select_one('._1waRmo')
            if topic:
                print(1)
                d = {'Titles': topic.text.replace("\n", "")}
                print(2)
                l.append(d)
                return d
    except:
        d = None

findDiv()
print(l)

Это хорошо перечисляет локальный файл. Когда я попытался с указанным URL-адресом, веб-сайт не возвращал отображаемый вами HTML-код.

from requests import get
from bs4 import BeautifulSoup

url = 'path_in_here\\test.html'
l = []

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}

example = open(url,"r")
text = example.read()

#response = get(url, headers=headers)
#html_soup = BeautifulSoup(response.text, 'html.parser')
html_soup = BeautifulSoup(text, 'html.parser')

print (text)

def findDiv():
    #try:
        print("finding toplevel")
        toplevel = html_soup.find("div", { "class":  "_25qBG5"} )
        print ("found toplevel")
        divs = toplevel.findChildren("div", recursive=True)
        print("found divs")

        for container in divs:
            print ("loop")
            topic = container.select_one('.1waRmo')
            if topic:
                print(1)
                d = {'Titles': topic.text.replace("\n", "")}
                print(2)
                l.append(d)
                return d
    #except:
    #    d = None
    #    print ("error")

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