Q:

How to search for the Particular Links using regex in python

I am scraping a website using python3.5.1 and BeautifulSoup
I want to search for the particular link using regex:
My code:
from bs4 import BeautifulSoup
import urllib.request
import re
r = urllib.request.urlopen('http://i.cantonfair.org.cn/en/expexhibitorlist.aspx?categoryno=404').read()
soup = BeautifulSoup(r,"html.parser")
links = soup.find_all("a", href=re.compile(r"ExpExhibitorList\.aspx\?categoryno=[0-9]+"))    
linksfromcategories = ([link["href"] for link in links])
print(linksfromcategories)

I get all the similar links
['/cn/ExpExhibitorList.aspx?categoryno=432', 'ExpExhibitorList.aspx?categoryno=432003']

But I do not want 
'/cn/ExpExhibitorList.aspx?categoryno=432'

to be searched 

A:

Just use anchors in your regex.
links = soup.find_all("a", href=re.compile(r"^ExpExhibitorList\.aspx\?categoryno=[0-9]+$"))

This would match all the a tags which has an exact value matched by the above regex.

