【问题标题】:python crawl one pagepython抓取一页
【发布时间】:2019-01-23 14:06:43
【问题描述】:

我试图提取以特定单词开头的提取链接(href),但即使我在页面源中有很多满足条件的链接,它也会返回空列表,我肯定遗漏了一些东西,下面是我的代码:

import requests
from bs4 import BeautifulSoup
import string
import os
import re

def extract_href_page(page):
    soup = BeautifulSoup(page)

    all_links = []
    links = soup.find_all('a', pattern = re.compile(r'\w*first_word'))
    # pattern = re.compile(r'\w*recette')
    print(links)
    for link in links:
          all_links.append(link['href'])  # Save href only, for example.
    return all_links

for page_number in range(1, 63):
    requete = requests.get ("https://www.website.com/pages/"+ "page".capitalize()+ "-" + str(page_number)  + ".html")
    page = requete.content
    list_links = extract_href_page(page)
    print(list_links)
    for link in list_links:
         print(link)

【问题讨论】:

  • 请正确格式化您的代码。
  • 我是 stackoverflow 的新手,对我来说它的格式很好
  • 您尝试访问的页面不存在:https://www.website.com/pages/Page-1.html

标签: python regex beautifulsoup python-requests


【解决方案1】:

试试这个:

import requests 
from bs4 import BeautifulSoup 
import string 
import os 
import re 
def extract_href_page(page): 
    soup = BeautifulSoup(page)  
    all_links = [] 
    links = soup.find_all('a', href=True) 
    # pattern = re.compile(r'\w*recette') 
    print(links) 
    for link in links: 
        if re.match(r"\w*first_word", link["href"], re.I):
            all_links.append(link.get("href"))
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-12
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多