我正在尝试使用python3为我的wordpress网站创建一个爬虫程序

2024-09-30 16:23:41 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests
from bs4 import BeautifulSoup

def page(current_page):
    current = "h2"
    while current == current_page:
        url = 'https://vishrantkhanna.com/?s=' + str(current)
        source_code = requests.get(url)
        plain_text = source_code.txt
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('h2', {'class': 'entry-title'}):
            href = "https://vishrantkhanna.com/" + link.get('href')
            title = link.string
            print(href)
            print(title)

page("h2")

我正在尝试复制和打印文章标题以及与之关联的href链接。你知道吗


Tags: httpsimportcomurlsourcetitlepagelink
1条回答
网友
1楼 · 发布于 2024-09-30 16:23:41

您需要从标题中提取<a>标记:

import requests
from bs4 import BeautifulSoup

URL = 'https://vishrantkhanna.com/?s=1'

html = requests.get(URL).text
bs = BeautifulSoup(html, 'html.parser')
for link in bs.find_all('h2', {'class': 'entry-title'}):
    a = link.find('a', href=True)
    href = "https://vishrantkhanna.com/" + a.get('href')
    title = link.string
    print(href)
    print(title)

相关问题 更多 >