简体   繁体   中英

scraping with BS4

code generates empty file. Possibly missing correct div/tag entries(?). Trying to scrape multiple pages on one site.

import requests
from bs4 import BeautifulSoup
import pandas as pd

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36 Edg/91.0.864.71'}

questionlist = []

def getQuestions(tag, page):
    url = f'https://www.tradepractitioner.com/tag/{tag}'
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    questions = soup.find_all('div', {'class': 'main grid '})
    for item in questions:
        question = {
        'title': item.find('a', {'class': 'post-title'}).text,
        'status': item.find('a', {'class': 'post-content'}).text,
         }
        questionlist.append(question)
    return

for x in range(1,5):
    getQuestions('cfius', x)
 

df = pd.DataFrame(questionlist)
df.to_excel('stackquestions.xlsx', index=False)
print('End.')

You have a trailing whitespace:

Replace:

questions = soup.find_all('div', {'class': 'main grid '})  # <- HERE " '"

By:

questions = soup.find_all('div', {'class': 'main grid'})

Now you have another problem:

AttributeError: 'NoneType' object has no attribute 'text'

Solution

questions = soup.find_all('article', {'class': 'post'})
for question in questions:
    question = {'title': question.find('h1', {'class': 'post-title'}).find('a').text,
                'status': question.find('section', {'class': 'post-content'}).find(text=True)}
    questionlist.append(question)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM