Beautifulsoup запросы .get () перенаправляет с указанного URL - PullRequest
0 голосов
/ 04 января 2019

Я использую

requests.get('https://www.pastemagazine.com/search?t=tweets+of+the+week&m=Lists')

, например, так:

import requests
from bs4 import BeautifulSoup
url = 'https://www.pastemagazine.com/search?t=tweets+of+the+week&m=Lists'
thepage = requests.get(url)
urlsoup = BeautifulSoup(thepage.text, "html.parser")
print(urlsoup.find_all("a", attrs={"class": "large-3 medium-3 cell image"})[0])

Но он продолжает очищаться не с полного URL, а только с домашней страницы ('https://www.pastemagazine.com'). Я могу сказать, потому что я ожидаю, что оператор print напечатает:

<a class="large-3 medium-3 cell image" href="/articles/2018/12/the-funniest-tweets-of-the-week-109.html" aria-label="">
    <picture data-sizes="[&quot;(min-width: 40em)&quot;,&quot;(min-width: 64em)&quot;]" class="lazyload" data-sources="[&quot;https://cdn.pastemagazine.com/www/opt/120/dogcrp-72x72.jpg&quot;,&quot;https://cdn.pastemagazine.com/www/opt/120/dogcrp-151x151.jpg&quot;,&quot;https://cdn.pastemagazine.com/www/opt/120/dogcrp-151x151.jpg&quot;]">
      <img alt="" />
    </picture>
  </a>

Но вместо этого он печатает:

<a aria-label='Daily Dose: Michael Chapman feat. Bridget St. John, "After All This Time"' class="large-3 medium-3 cell image" href="/articles/2019/01/daily-dose-michael-chapman-feat-bridget-st-john-af.html"> 
    <picture class="lazyload" data-sizes='["(min-width: 40em)","(min-width: 64em)"]' data-sources='["https://cdn.pastemagazine.com/www/opt/300/MichaelChapman2019_ConstanceMensh_Square-72x72.jpg","https://cdn.pastemagazine.com/www/opt/300/MichaelChapman2019_ConstanceMensh_Square-151x151.jpg","https://cdn.pastemagazine.com/www/opt/300/MichaelChapman2019_ConstanceMensh_Square-151x151.jpg"]'>
      <img alt='Daily Dose: Michael Chapman feat. Bridget St. John, "After All This Time"'/>
    </picture>
  </a>

Что соответствует элементу на домашней странице, а не конкретному URLЯ хочу покончить с поисковыми терминами. Почему он перенаправляет на домашнюю страницу? Как я могу помешать этому?

Ответы [ 2 ]

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

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

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

url = "https://www.pastemagazine.com/search?t=tweets+of+the+week&m=Lists"

with requests.Session() as s:
    res = s.get(url,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(res.text,'lxml')
    for item in set([urljoin(url,item.get("href")) for item in soup.select("ul.articles a[href*='tweets-of-the-week']")]):
        print(item)

Или, чтобы сделать его еще проще, обновите следующие библиотеки:

pip3 install lxml --upgrade
pip3 install beautifulsoup4 --upgrade

А затем попробуйте:

with requests.Session() as s:
    res = s.get(url,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(res.text,'lxml')
    for item in soup.select("a.noimage[href*='tweets-of-the-week']"):
        print(urljoin(url,item.get("href")))
0 голосов
/ 04 января 2019

Если вы уверены в части перенаправления, вы можете установить allow_redirects на False, чтобы предотвратить перенаправление.

r = requests.get(url, allow_redirects=False)
...